From 58f4abbce581a736ef704a0db4acc23084720c89 Mon Sep 17 00:00:00 2001 From: Yvonnick Esnault Date: Sat, 21 Jan 2017 18:02:11 +0100 Subject: [PATCH] chore(tatcli): move tatcli into tat repo --- .travis.yml | 9 + docs/build/content/overview/architecture.md | 2 +- docs/build/content/overview/contribute.md | 2 +- docs/build/content/overview/introduction.md | 2 +- docs/build/content/sdk/golang-full-example.md | 2 +- docs/build/content/tatcli/general.md | 2 +- docs/build/static/json/search.json | 10 +- docs/ecosystem/al2tat/index.html | 2 +- docs/ecosystem/index.html | 2 +- docs/ecosystem/index.xml | 4 +- docs/ecosystem/mail2tat/index.html | 2 +- docs/ecosystem/tat2es/index.html | 2 +- docs/ecosystem/tat2xmpp/index.html | 2 +- docs/ecosystem/tatdashing/index.html | 2 +- docs/engine/api-groups/index.html | 2 +- docs/engine/api-messages/index.html | 2 +- docs/engine/api-presences/index.html | 2 +- docs/engine/api-system/index.html | 2 +- docs/engine/api-topics/index.html | 6 +- docs/engine/api-users/index.html | 2 +- docs/engine/general/index.html | 2 +- docs/engine/index.html | 2 +- docs/engine/index.xml | 8 +- .../engine/production-installation/index.html | 2 +- docs/engine/simple-installation/index.html | 2 +- docs/index.html | 2 +- docs/index.xml | 733 ++- docs/json/search.json | 10 +- docs/overview/architecture/index.html | 4 +- docs/overview/concepts/index.html | 2 +- docs/overview/contribute/index.html | 4 +- docs/overview/index.html | 2 +- docs/overview/index.xml | 10 +- docs/overview/introduction/index.html | 4 +- docs/overview/lifecycle/index.html | 2 +- docs/sdk/full-example/index.html | 2 +- docs/sdk/golang-full-example/index.html | 4 +- docs/sdk/golang-simple-main/index.html | 2 +- docs/sdk/index.html | 2 +- docs/sdk/index.xml | 6 +- docs/sitemap.xml | 92 +- docs/tatcli/general/index.html | 4 +- docs/tatcli/index.html | 2 +- docs/tatcli/index.xml | 8 +- docs/tatcli/tatcli-config/index.html | 2 +- docs/tatcli/tatcli-group/index.html | 2 +- docs/tatcli/tatcli-message/index.html | 2 +- docs/tatcli/tatcli-presence/index.html | 2 +- docs/tatcli/tatcli-stats/index.html | 2 +- docs/tatcli/tatcli-system/index.html | 2 +- docs/tatcli/tatcli-topic/index.html | 4 +- docs/tatcli/tatcli-ui/index.html | 2 +- docs/tatcli/tatcli-update/index.html | 2 +- docs/tatcli/tatcli-user/index.html | 2 +- docs/tatcli/tatcli-version/index.html | 2 +- docs/tatnhack/index.html | 2 +- docs/tatnhack/index.xml | 4 +- docs/tatnhack/monitoring-process/index.html | 2 +- docs/tatnhack/visual-feedback/index.html | 2 +- docs/tatwebui/cdsview/index.html | 2 +- docs/tatwebui/dashingview/index.html | 2 +- docs/tatwebui/development/index.html | 2 +- docs/tatwebui/index.html | 2 +- docs/tatwebui/index.xml | 4 +- docs/tatwebui/introduction/index.html | 2 +- docs/tatwebui/monitoringview/index.html | 2 +- docs/tatwebui/notificationsview/index.html | 2 +- docs/tatwebui/pastatview/index.html | 2 +- docs/tatwebui/releaseview/index.html | 2 +- docs/tatwebui/standardview/index.html | 2 +- package.sh | 16 + tatcli/.gitignore | 3 + tatcli/.travis.yml | 32 + tatcli/CONTRIBUTING.md | 82 + tatcli/LICENSE | 25 + tatcli/README.md | 18 + tatcli/config/config.go | 18 + tatcli/config/show.go | 24 + tatcli/config/write.go | 70 + tatcli/group/add_admin_user.go | 19 + tatcli/group/add_user.go | 19 + tatcli/group/create.go | 24 + tatcli/group/delete.go | 18 + tatcli/group/delete_admin_user.go | 19 + tatcli/group/delete_user.go | 19 + tatcli/group/group.go | 22 + tatcli/group/list.go | 17 + tatcli/group/update.go | 22 + tatcli/internal/config.go | 51 + tatcli/internal/engine.go | 92 + tatcli/internal/utils.go | 12 + tatcli/main.go | 68 + tatcli/message/add.go | 61 + tatcli/message/concat.go | 31 + tatcli/message/delete.go | 30 + tatcli/message/delete_bulk.go | 69 + tatcli/message/label.go | 37 + tatcli/message/like.go | 22 + tatcli/message/list.go | 145 + tatcli/message/message.go | 35 + tatcli/message/move.go | 22 + tatcli/message/relabel.go | 51 + tatcli/message/reply.go | 31 + tatcli/message/task.go | 24 + tatcli/message/unlabel.go | 25 + tatcli/message/unlike.go | 22 + tatcli/message/untask.go | 22 + tatcli/message/unvotedown.go | 22 + tatcli/message/unvoteup.go | 22 + tatcli/message/update.go | 31 + tatcli/message/votedown.go | 22 + tatcli/message/voteup.go | 22 + tatcli/package.sh | 14 + tatcli/presence/add.go | 25 + tatcli/presence/delete.go | 19 + tatcli/presence/list.go | 21 + tatcli/presence/presence.go | 17 + tatcli/release.sh | 49 + tatcli/stats/count.go | 21 + tatcli/stats/db_collections.go | 21 + tatcli/stats/db_replset_config.go | 21 + tatcli/stats/db_replset_status.go | 21 + tatcli/stats/db_server_status.go | 21 + tatcli/stats/db_slowest_queries.go | 21 + tatcli/stats/db_stats.go | 20 + tatcli/stats/distribution_topics.go | 75 + tatcli/stats/instance.go | 21 + tatcli/stats/stats.go | 23 + tatcli/system/cache_clean.go | 20 + tatcli/system/cache_info.go | 20 + tatcli/system/system.go | 16 + tatcli/tests.sh | 68 + tatcli/topic/add_admin_group.go | 23 + tatcli/topic/add_admin_user.go | 23 + tatcli/topic/add_parameter.go | 35 + tatcli/topic/add_ro_group.go | 23 + tatcli/topic/add_ro_user.go | 23 + tatcli/topic/add_rw_group.go | 23 + tatcli/topic/add_rw_user.go | 23 + tatcli/topic/all_compute_labels.go | 18 + tatcli/topic/all_compute_replies.go | 18 + tatcli/topic/all_compute_tags.go | 18 + tatcli/topic/all_set_param.go | 23 + tatcli/topic/compute_labels.go | 23 + tatcli/topic/compute_tags.go | 23 + tatcli/topic/create.go | 29 + tatcli/topic/delete.go | 21 + tatcli/topic/delete_admin_group.go | 23 + tatcli/topic/delete_admin_user.go | 23 + tatcli/topic/delete_parameter.go | 23 + tatcli/topic/delete_ro_group.go | 23 + tatcli/topic/delete_ro_user.go | 23 + tatcli/topic/delete_rw_group.go | 23 + tatcli/topic/delete_rw_user.go | 23 + tatcli/topic/list.go | 48 + tatcli/topic/parameter.go | 58 + tatcli/topic/topic.go | 45 + tatcli/topic/truncate.go | 57 + tatcli/topic/truncate_labels.go | 23 + tatcli/topic/truncate_tags.go | 23 + tatcli/ui/cmd.go | 33 + tatcli/ui/config.go | 144 + tatcli/ui/events.go | 447 ++ tatcli/ui/home.go | 141 + tatcli/ui/message.go | 116 + tatcli/ui/messages.go | 585 ++ tatcli/ui/result.go | 28 + tatcli/ui/send.go | 414 ++ tatcli/ui/topics.go | 169 + tatcli/ui/ui.go | 315 ++ tatcli/update/cmd.go | 90 + tatcli/user/add.go | 28 + tatcli/user/add_contact.go | 20 + tatcli/user/add_favorite_tag.go | 20 + tatcli/user/add_favorite_topic.go | 20 + tatcli/user/archive.go | 19 + tatcli/user/check.go | 40 + tatcli/user/contacts.go | 25 + tatcli/user/convert_to_system.go | 31 + .../user/disable_notifications_all_topics.go | 16 + tatcli/user/disable_notifications_topic.go | 20 + .../user/enable_notifications_all_topics.go | 16 + tatcli/user/enable_notifications_topic.go | 20 + tatcli/user/list.go | 29 + tatcli/user/me.go | 16 + tatcli/user/remove_contact.go | 20 + tatcli/user/remove_favorite_tag.go | 20 + tatcli/user/remove_favorite_topic.go | 20 + tatcli/user/rename.go | 24 + tatcli/user/reset.go | 25 + tatcli/user/set_admin.go | 23 + tatcli/user/system_reset.go | 23 + tatcli/user/update.go | 27 + tatcli/user/update_system.go | 31 + tatcli/user/user.go | 40 + tatcli/user/verify.go | 50 + tatcli/version/version.go | 41 + types.go | 4 +- vendor/github.com/Shopify/sarama/CHANGELOG.md | 27 + vendor/github.com/Shopify/sarama/consumer.go | 4 +- .../Shopify/sarama/produce_request.go | 4 +- vendor/github.com/Sirupsen/logrus/README.md | 5 +- .../Sirupsen/logrus/text_formatter.go | 12 +- .../hashtag => briandowns/spinner}/LICENSE | 30 +- .../github.com/briandowns/spinner/README.md | 194 + .../briandowns/spinner/character_sets.go | 42 + .../github.com/briandowns/spinner/spinner.go | 198 + .../eapache/go-resiliency/retrier/README.md | 26 - .../eapache/go-resiliency/retrier/backoffs.go | 24 - .../go-resiliency/retrier/classifier.go | 66 - .../eapache/go-resiliency/retrier/retrier.go | 69 - vendor/github.com/fatih/color/LICENSE.md | 20 + vendor/github.com/fatih/color/README.md | 175 + vendor/github.com/fatih/color/color.go | 510 ++ vendor/github.com/fatih/color/doc.go | 128 + .../github.com/fsnotify/fsnotify/fsnotify.go | 4 + .../github.com/fsnotify/fsnotify/inotify.go | 9 + vendor/github.com/gin-gonic/gin/README.md | 43 +- vendor/github.com/gin-gonic/gin/codecov.yml | 5 + vendor/github.com/gin-gonic/gin/context.go | 43 +- vendor/github.com/gin-gonic/gin/logger.go | 16 +- vendor/github.com/gin-gonic/gin/mode.go | 4 +- .../golang/protobuf/proto/decode.go | 117 +- .../golang/protobuf/proto/encode.go | 25 +- .../github.com/golang/protobuf/proto/equal.go | 8 +- .../golang/protobuf/proto/extensions.go | 4 + .../github.com/golang/protobuf/proto/lib.go | 2 +- .../golang/protobuf/proto/properties.go | 10 +- .../golang/protobuf/proto/text_parser.go | 23 +- vendor/github.com/hashicorp/hcl/decoder.go | 14 +- .../hashicorp/hcl/hcl/parser/parser.go | 33 +- .../hashicorp/hcl/hcl/scanner/scanner.go | 8 +- .../hashicorp/hcl/hcl/strconv/quote.go | 19 +- .../hashicorp/hcl/json/parser/flatten.go | 6 + .../hashicorp/hcl/json/parser/parser.go | 1 + .../inconshreveable/mousetrap/LICENSE | 13 - .../inconshreveable/mousetrap/README.md | 23 - .../inconshreveable/mousetrap/trap_others.go | 15 - .../inconshreveable/mousetrap/trap_windows.go | 98 - .../mousetrap/trap_windows_1.4.go | 46 - vendor/github.com/jinzhu/now/README.md | 6 + vendor/github.com/kr/fs/LICENSE | 27 - vendor/github.com/kr/fs/Readme | 3 - vendor/github.com/kr/fs/filesystem.go | 36 - vendor/github.com/kr/fs/walk.go | 95 - .../magiconair/properties/CHANGELOG.md | 9 + .../magiconair/properties/README.md | 2 +- .../magiconair/properties/decode.go | 19 +- .../github.com/magiconair/properties/doc.go | 2 +- .../magiconair/properties/integrate.go | 2 +- .../github.com/magiconair/properties/lex.go | 21 +- .../github.com/magiconair/properties/load.go | 8 +- .../magiconair/properties/parser.go | 2 +- .../magiconair/properties/properties.go | 23 +- .../magiconair/properties/rangecheck.go | 2 +- vendor/github.com/mattn/go-colorable/LICENSE | 21 + .../github.com/mattn/go-colorable/README.md | 43 + .../mattn/go-colorable/colorable_others.go | 27 + .../mattn/go-colorable/colorable_windows.go | 820 +++ .../mattn/go-colorable/noncolorable.go | 61 + vendor/github.com/mattn/go-isatty/LICENSE | 9 + vendor/github.com/mattn/go-isatty/README.md | 37 + vendor/github.com/mattn/go-isatty/doc.go | 2 + .../mattn/go-isatty/isatty_appengine.go | 9 + .../github.com/mattn/go-isatty/isatty_bsd.go | 18 + .../mattn/go-isatty/isatty_linux.go | 18 + .../mattn/go-isatty/isatty_solaris.go | 16 + .../mattn/go-isatty/isatty_windows.go | 19 + vendor/github.com/mattn/go-runewidth/LICENSE | 21 + .../github.com/mattn/go-runewidth/README.mkd | 27 + .../mattn/go-runewidth/runewidth.go | 481 ++ .../mattn/go-runewidth/runewidth_js.go | 8 + .../mattn/go-runewidth/runewidth_posix.go | 77 + .../mattn/go-runewidth/runewidth_windows.go | 25 + .../mitchellh/mapstructure/mapstructure.go | 62 +- vendor/github.com/mvdan/xurls/LICENSE | 27 - vendor/github.com/mvdan/xurls/README.md | 40 - vendor/github.com/mvdan/xurls/regex.go | 8 - vendor/github.com/mvdan/xurls/schemes.go | 17 - vendor/github.com/mvdan/xurls/tlds.go | 1564 ------ vendor/github.com/mvdan/xurls/tlds_pseudo.go | 25 - vendor/github.com/mvdan/xurls/xurls.go | 66 - .../olekukonko/tablewriter/LICENCE.md | 19 + .../olekukonko/tablewriter/README.md | 204 + .../github.com/olekukonko/tablewriter/csv.go | 52 + .../olekukonko/tablewriter/table.go | 662 +++ .../olekukonko/tablewriter/test.csv | 4 + .../olekukonko/tablewriter/test_info.csv | 4 + .../github.com/olekukonko/tablewriter/util.go | 72 + .../github.com/olekukonko/tablewriter/wrap.go | 103 + vendor/github.com/pelletier/go-toml/README.md | 2 +- .../pelletier/go-toml/keysparsing.go | 11 +- vendor/github.com/pelletier/go-toml/lexer.go | 44 +- vendor/github.com/pelletier/go-toml/parser.go | 71 +- .../pelletier/go-toml/tomltree_conversions.go | 77 +- vendor/github.com/pkg/errors/LICENSE | 23 - vendor/github.com/pkg/errors/README.md | 52 - vendor/github.com/pkg/errors/appveyor.yml | 32 - vendor/github.com/pkg/errors/errors.go | 269 - vendor/github.com/pkg/errors/stack.go | 178 - vendor/github.com/pkg/sftp/CONTRIBUTORS | 2 - vendor/github.com/pkg/sftp/README.md | 27 - vendor/github.com/pkg/sftp/attrs.go | 237 - vendor/github.com/pkg/sftp/attrs_stubs.go | 11 - vendor/github.com/pkg/sftp/attrs_unix.go | 17 - vendor/github.com/pkg/sftp/client.go | 1128 ---- vendor/github.com/pkg/sftp/conn.go | 122 - vendor/github.com/pkg/sftp/debug.go | 9 - vendor/github.com/pkg/sftp/packet.go | 901 --- vendor/github.com/pkg/sftp/release.go | 5 - vendor/github.com/pkg/sftp/server.go | 607 --- .../pkg/sftp/server_statvfs_darwin.go | 21 - .../pkg/sftp/server_statvfs_impl.go | 25 - .../pkg/sftp/server_statvfs_linux.go | 22 - .../pkg/sftp/server_statvfs_stubs.go | 11 - vendor/github.com/pkg/sftp/server_stubs.go | 12 - vendor/github.com/pkg/sftp/server_unix.go | 143 - vendor/github.com/pkg/sftp/sftp.go | 217 - vendor/github.com/pmezard/go-difflib/LICENSE | 27 - .../pmezard/go-difflib/difflib/difflib.go | 758 --- vendor/github.com/spf13/afero/README.md | 10 +- vendor/github.com/spf13/afero/afero.go | 2 +- vendor/github.com/spf13/afero/basepath.go | 26 +- .../github.com/spf13/afero/cacheOnReadFs.go | 3 +- vendor/github.com/spf13/afero/mem/file.go | 4 +- vendor/github.com/spf13/afero/memmap.go | 58 +- vendor/github.com/spf13/afero/sftp.go | 128 - vendor/github.com/spf13/afero/sftp/file.go | 95 - vendor/github.com/spf13/afero/sftp_test_go | 286 - vendor/github.com/spf13/cast/caste.go | 13 +- vendor/github.com/spf13/cobra/README.md | 15 +- .../spf13/cobra/bash_completions.md | 2 +- vendor/github.com/spf13/cobra/command.go | 22 +- .../spf13/jwalterweatherman/README.md | 33 +- .../jwalterweatherman/default_notepad.go | 113 + .../spf13/jwalterweatherman/log_counter.go | 56 + .../spf13/jwalterweatherman/notepad.go | 195 + .../thatswhyyoualwaysleaveanote.go | 256 - vendor/github.com/spf13/pflag/README.md | 6 +- vendor/github.com/spf13/pflag/flag.go | 66 +- vendor/github.com/spf13/viper/util.go | 51 +- vendor/github.com/spf13/viper/viper.go | 148 +- vendor/github.com/stretchr/testify/LICENSE | 22 - .../testify/assert/assertion_forward.go | 387 -- .../testify/assert/assertion_forward.go.tmpl | 4 - .../stretchr/testify/assert/assertions.go | 1007 ---- .../github.com/stretchr/testify/assert/doc.go | 45 - .../stretchr/testify/assert/errors.go | 10 - .../testify/assert/forward_assertions.go | 16 - .../testify/assert/http_assertions.go | 106 - vendor/github.com/yesnault/hashtag/README.md | 39 - vendor/github.com/yesnault/hashtag/hashtag.go | 201 - vendor/github.com/yesnault/hashtag/tests.yml | 475 -- vendor/golang.org/x/crypto/LICENSE | 27 - vendor/golang.org/x/crypto/PATENTS | 22 - .../x/crypto/curve25519/const_amd64.s | 20 - .../x/crypto/curve25519/cswap_amd64.s | 88 - .../x/crypto/curve25519/curve25519.go | 841 --- vendor/golang.org/x/crypto/curve25519/doc.go | 23 - .../x/crypto/curve25519/freeze_amd64.s | 94 - .../x/crypto/curve25519/ladderstep_amd64.s | 1398 ----- .../x/crypto/curve25519/mont25519_amd64.go | 240 - .../x/crypto/curve25519/mul_amd64.s | 191 - .../x/crypto/curve25519/square_amd64.s | 153 - vendor/golang.org/x/crypto/ed25519/ed25519.go | 181 - .../ed25519/internal/edwards25519/const.go | 1422 ----- .../internal/edwards25519/edwards25519.go | 1771 ------ vendor/golang.org/x/crypto/ssh/buffer.go | 98 - vendor/golang.org/x/crypto/ssh/certs.go | 503 -- vendor/golang.org/x/crypto/ssh/channel.go | 633 --- vendor/golang.org/x/crypto/ssh/cipher.go | 579 -- vendor/golang.org/x/crypto/ssh/client.go | 213 - vendor/golang.org/x/crypto/ssh/client_auth.go | 473 -- vendor/golang.org/x/crypto/ssh/common.go | 356 -- vendor/golang.org/x/crypto/ssh/connection.go | 143 - vendor/golang.org/x/crypto/ssh/doc.go | 18 - vendor/golang.org/x/crypto/ssh/handshake.go | 460 -- vendor/golang.org/x/crypto/ssh/kex.go | 540 -- vendor/golang.org/x/crypto/ssh/keys.go | 880 --- vendor/golang.org/x/crypto/ssh/mac.go | 57 - vendor/golang.org/x/crypto/ssh/messages.go | 758 --- vendor/golang.org/x/crypto/ssh/mux.go | 330 -- vendor/golang.org/x/crypto/ssh/server.go | 488 -- vendor/golang.org/x/crypto/ssh/session.go | 627 --- vendor/golang.org/x/crypto/ssh/tcpip.go | 407 -- vendor/golang.org/x/crypto/ssh/transport.go | 333 -- .../golang.org/x/sys/unix/asm_linux_mipsx.s | 31 + .../x/sys/unix/flock_linux_32bit.go | 2 +- vendor/golang.org/x/sys/unix/mkerrors.sh | 2 + .../golang.org/x/sys/unix/mksysnum_linux.pl | 12 +- vendor/golang.org/x/sys/unix/syscall_bsd.go | 18 +- vendor/golang.org/x/sys/unix/syscall_linux.go | 44 +- .../x/sys/unix/syscall_linux_amd64.go | 5 - .../x/sys/unix/syscall_linux_amd64_gc.go | 13 + .../x/sys/unix/syscall_linux_mipsx.go | 241 + vendor/golang.org/x/sys/unix/syscall_unix.go | 5 - .../golang.org/x/sys/unix/syscall_unix_gc.go | 15 + vendor/golang.org/x/sys/unix/types_linux.go | 6 +- .../x/sys/unix/zerrors_linux_386.go | 19 + .../x/sys/unix/zerrors_linux_amd64.go | 19 + .../x/sys/unix/zerrors_linux_arm.go | 19 + .../x/sys/unix/zerrors_linux_arm64.go | 19 + .../x/sys/unix/zerrors_linux_mips.go | 1814 +++++++ .../x/sys/unix/zerrors_linux_mipsle.go | 2020 +++++++ .../x/sys/unix/zerrors_linux_ppc64.go | 19 + .../x/sys/unix/zerrors_linux_ppc64le.go | 19 + .../x/sys/unix/zerrors_linux_s390x.go | 19 + .../x/sys/unix/zerrors_linux_sparc64.go | 19 + .../x/sys/unix/zsyscall_linux_386.go | 15 +- .../x/sys/unix/zsyscall_linux_amd64.go | 15 +- .../x/sys/unix/zsyscall_linux_arm.go | 15 +- .../x/sys/unix/zsyscall_linux_arm64.go | 15 +- .../x/sys/unix/zsyscall_linux_mips.go | 1829 +++++++ .../x/sys/unix/zsyscall_linux_mips64.go | 15 +- .../x/sys/unix/zsyscall_linux_mips64le.go | 15 +- .../x/sys/unix/zsyscall_linux_mipsle.go | 1829 +++++++ .../x/sys/unix/zsyscall_linux_ppc64.go | 15 +- .../x/sys/unix/zsyscall_linux_ppc64le.go | 15 +- .../x/sys/unix/zsyscall_linux_s390x.go | 21 +- .../x/sys/unix/zsyscall_linux_sparc64.go | 21 +- .../x/sys/unix/zsysnum_linux_mips.go | 359 ++ .../x/sys/unix/zsysnum_linux_mipsle.go | 359 ++ .../golang.org/x/sys/unix/ztypes_linux_386.go | 8 + .../x/sys/unix/ztypes_linux_amd64.go | 8 + .../golang.org/x/sys/unix/ztypes_linux_arm.go | 19 +- .../x/sys/unix/ztypes_linux_arm64.go | 8 + .../x/sys/unix/ztypes_linux_mips.go | 642 +++ .../x/sys/unix/ztypes_linux_mips64.go | 8 + .../x/sys/unix/ztypes_linux_mips64le.go | 8 + .../x/sys/unix/ztypes_linux_mipsle.go | 642 +++ .../x/sys/unix/ztypes_linux_ppc64.go | 8 + .../x/sys/unix/ztypes_linux_ppc64le.go | 8 + .../x/sys/unix/ztypes_linux_s390x.go | 8 + .../x/sys/unix/ztypes_linux_sparc64.go | 8 + .../x/text/unicode/norm/readwriter.go | 1 - vendor/gopkg.in/bsm/ratelimit.v1/Makefile | 16 - vendor/gopkg.in/bsm/ratelimit.v1/README.md | 54 - vendor/gopkg.in/bsm/ratelimit.v1/ratelimit.go | 96 - .../sftp => gopkg.in/cheggaaa/pb.v1}/LICENSE | 11 +- vendor/gopkg.in/cheggaaa/pb.v1/README.md | 176 + vendor/gopkg.in/cheggaaa/pb.v1/format.go | 87 + vendor/gopkg.in/cheggaaa/pb.v1/pb.go | 444 ++ .../gopkg.in/cheggaaa/pb.v1/pb_appengine.go | 11 + vendor/gopkg.in/cheggaaa/pb.v1/pb_nix.go | 8 + vendor/gopkg.in/cheggaaa/pb.v1/pb_solaris.go | 6 + vendor/gopkg.in/cheggaaa/pb.v1/pb_win.go | 141 + vendor/gopkg.in/cheggaaa/pb.v1/pb_x.go | 110 + vendor/gopkg.in/cheggaaa/pb.v1/pool.go | 76 + vendor/gopkg.in/cheggaaa/pb.v1/pool_win.go | 35 + vendor/gopkg.in/cheggaaa/pb.v1/pool_x.go | 22 + vendor/gopkg.in/cheggaaa/pb.v1/reader.go | 25 + vendor/gopkg.in/cheggaaa/pb.v1/runecount.go | 17 + vendor/gopkg.in/cheggaaa/pb.v1/termios_bsd.go | 9 + vendor/gopkg.in/cheggaaa/pb.v1/termios_nix.go | 7 + .../go-playground/validator.v8/README.md | 61 +- .../go-playground/validator.v8/baked_in.go | 28 +- .../go-playground/validator.v8/cache.go | 280 +- .../go-playground/validator.v8/doc.go | 2 +- .../go-playground/validator.v8/util.go | 190 +- .../go-playground/validator.v8/validator.go | 447 +- vendor/gopkg.in/mgo.v2/LICENSE | 25 - vendor/gopkg.in/mgo.v2/Makefile | 5 - vendor/gopkg.in/mgo.v2/README.md | 4 - vendor/gopkg.in/mgo.v2/auth.go | 467 -- vendor/gopkg.in/mgo.v2/bson/LICENSE | 25 - vendor/gopkg.in/mgo.v2/bson/bson.go | 738 --- vendor/gopkg.in/mgo.v2/bson/decimal.go | 310 -- vendor/gopkg.in/mgo.v2/bson/decode.go | 849 --- vendor/gopkg.in/mgo.v2/bson/encode.go | 514 -- vendor/gopkg.in/mgo.v2/bson/json.go | 380 -- vendor/gopkg.in/mgo.v2/bulk.go | 351 -- vendor/gopkg.in/mgo.v2/cluster.go | 682 --- vendor/gopkg.in/mgo.v2/doc.go | 31 - vendor/gopkg.in/mgo.v2/gridfs.go | 761 --- vendor/gopkg.in/mgo.v2/internal/json/LICENSE | 27 - .../gopkg.in/mgo.v2/internal/json/decode.go | 1685 ------ .../gopkg.in/mgo.v2/internal/json/encode.go | 1256 ----- .../mgo.v2/internal/json/extension.go | 95 - vendor/gopkg.in/mgo.v2/internal/json/fold.go | 143 - .../gopkg.in/mgo.v2/internal/json/indent.go | 141 - .../gopkg.in/mgo.v2/internal/json/scanner.go | 697 --- .../gopkg.in/mgo.v2/internal/json/stream.go | 510 -- vendor/gopkg.in/mgo.v2/internal/json/tags.go | 44 - vendor/gopkg.in/mgo.v2/internal/sasl/sasl.c | 77 - vendor/gopkg.in/mgo.v2/internal/sasl/sasl.go | 138 - .../mgo.v2/internal/sasl/sasl_windows.c | 122 - .../mgo.v2/internal/sasl/sasl_windows.go | 142 - .../mgo.v2/internal/sasl/sasl_windows.h | 7 - .../mgo.v2/internal/sasl/sspi_windows.c | 96 - .../mgo.v2/internal/sasl/sspi_windows.h | 70 - .../gopkg.in/mgo.v2/internal/scram/scram.go | 266 - vendor/gopkg.in/mgo.v2/log.go | 133 - vendor/gopkg.in/mgo.v2/queue.go | 91 - vendor/gopkg.in/mgo.v2/raceoff.go | 5 - vendor/gopkg.in/mgo.v2/raceon.go | 5 - vendor/gopkg.in/mgo.v2/saslimpl.go | 11 - vendor/gopkg.in/mgo.v2/saslstub.go | 11 - vendor/gopkg.in/mgo.v2/server.go | 463 -- vendor/gopkg.in/mgo.v2/session.go | 4825 ----------------- vendor/gopkg.in/mgo.v2/socket.go | 707 --- vendor/gopkg.in/mgo.v2/stats.go | 147 - vendor/gopkg.in/redis.v4/LICENSE | 25 - vendor/gopkg.in/redis.v4/Makefile | 17 - vendor/gopkg.in/redis.v4/README.md | 127 - vendor/gopkg.in/redis.v4/cluster.go | 663 --- vendor/gopkg.in/redis.v4/command.go | 982 ---- vendor/gopkg.in/redis.v4/commands.go | 2073 ------- vendor/gopkg.in/redis.v4/doc.go | 4 - .../internal/consistenthash/consistenthash.go | 81 - .../redis.v4/internal/errors/errors.go | 67 - .../redis.v4/internal/hashtag/hashtag.go | 73 - vendor/gopkg.in/redis.v4/internal/log.go | 15 - .../gopkg.in/redis.v4/internal/pool/conn.go | 67 - .../gopkg.in/redis.v4/internal/pool/pool.go | 384 -- .../redis.v4/internal/pool/pool_single.go | 55 - .../redis.v4/internal/pool/pool_sticky.go | 137 - .../gopkg.in/redis.v4/internal/proto/proto.go | 122 - .../redis.v4/internal/proto/reader.go | 264 - .../redis.v4/internal/proto/writebuffer.go | 101 - vendor/gopkg.in/redis.v4/internal/util.go | 27 - vendor/gopkg.in/redis.v4/iterator.go | 86 - vendor/gopkg.in/redis.v4/options.go | 113 - vendor/gopkg.in/redis.v4/parser.go | 379 -- vendor/gopkg.in/redis.v4/pipeline.go | 109 - vendor/gopkg.in/redis.v4/pubsub.go | 294 - vendor/gopkg.in/redis.v4/redis.go | 244 - vendor/gopkg.in/redis.v4/result.go | 140 - vendor/gopkg.in/redis.v4/ring.go | 397 -- vendor/gopkg.in/redis.v4/script.go | 52 - vendor/gopkg.in/redis.v4/sentinel.go | 333 -- vendor/gopkg.in/redis.v4/tx.go | 204 - vendor/vendor.json | 377 +- 532 files changed, 24094 insertions(+), 50914 deletions(-) create mode 100644 tatcli/.gitignore create mode 100644 tatcli/.travis.yml create mode 100644 tatcli/CONTRIBUTING.md create mode 100644 tatcli/LICENSE create mode 100644 tatcli/README.md create mode 100644 tatcli/config/config.go create mode 100644 tatcli/config/show.go create mode 100644 tatcli/config/write.go create mode 100644 tatcli/group/add_admin_user.go create mode 100644 tatcli/group/add_user.go create mode 100644 tatcli/group/create.go create mode 100644 tatcli/group/delete.go create mode 100644 tatcli/group/delete_admin_user.go create mode 100644 tatcli/group/delete_user.go create mode 100644 tatcli/group/group.go create mode 100644 tatcli/group/list.go create mode 100644 tatcli/group/update.go create mode 100644 tatcli/internal/config.go create mode 100644 tatcli/internal/engine.go create mode 100644 tatcli/internal/utils.go create mode 100644 tatcli/main.go create mode 100644 tatcli/message/add.go create mode 100644 tatcli/message/concat.go create mode 100644 tatcli/message/delete.go create mode 100644 tatcli/message/delete_bulk.go create mode 100644 tatcli/message/label.go create mode 100644 tatcli/message/like.go create mode 100644 tatcli/message/list.go create mode 100644 tatcli/message/message.go create mode 100644 tatcli/message/move.go create mode 100644 tatcli/message/relabel.go create mode 100644 tatcli/message/reply.go create mode 100644 tatcli/message/task.go create mode 100644 tatcli/message/unlabel.go create mode 100644 tatcli/message/unlike.go create mode 100644 tatcli/message/untask.go create mode 100644 tatcli/message/unvotedown.go create mode 100644 tatcli/message/unvoteup.go create mode 100644 tatcli/message/update.go create mode 100644 tatcli/message/votedown.go create mode 100644 tatcli/message/voteup.go create mode 100755 tatcli/package.sh create mode 100644 tatcli/presence/add.go create mode 100644 tatcli/presence/delete.go create mode 100644 tatcli/presence/list.go create mode 100644 tatcli/presence/presence.go create mode 100755 tatcli/release.sh create mode 100644 tatcli/stats/count.go create mode 100644 tatcli/stats/db_collections.go create mode 100644 tatcli/stats/db_replset_config.go create mode 100644 tatcli/stats/db_replset_status.go create mode 100644 tatcli/stats/db_server_status.go create mode 100644 tatcli/stats/db_slowest_queries.go create mode 100644 tatcli/stats/db_stats.go create mode 100644 tatcli/stats/distribution_topics.go create mode 100644 tatcli/stats/instance.go create mode 100644 tatcli/stats/stats.go create mode 100644 tatcli/system/cache_clean.go create mode 100644 tatcli/system/cache_info.go create mode 100644 tatcli/system/system.go create mode 100755 tatcli/tests.sh create mode 100644 tatcli/topic/add_admin_group.go create mode 100644 tatcli/topic/add_admin_user.go create mode 100644 tatcli/topic/add_parameter.go create mode 100644 tatcli/topic/add_ro_group.go create mode 100644 tatcli/topic/add_ro_user.go create mode 100644 tatcli/topic/add_rw_group.go create mode 100644 tatcli/topic/add_rw_user.go create mode 100644 tatcli/topic/all_compute_labels.go create mode 100644 tatcli/topic/all_compute_replies.go create mode 100644 tatcli/topic/all_compute_tags.go create mode 100644 tatcli/topic/all_set_param.go create mode 100644 tatcli/topic/compute_labels.go create mode 100644 tatcli/topic/compute_tags.go create mode 100644 tatcli/topic/create.go create mode 100644 tatcli/topic/delete.go create mode 100644 tatcli/topic/delete_admin_group.go create mode 100644 tatcli/topic/delete_admin_user.go create mode 100644 tatcli/topic/delete_parameter.go create mode 100644 tatcli/topic/delete_ro_group.go create mode 100644 tatcli/topic/delete_ro_user.go create mode 100644 tatcli/topic/delete_rw_group.go create mode 100644 tatcli/topic/delete_rw_user.go create mode 100644 tatcli/topic/list.go create mode 100644 tatcli/topic/parameter.go create mode 100644 tatcli/topic/topic.go create mode 100644 tatcli/topic/truncate.go create mode 100644 tatcli/topic/truncate_labels.go create mode 100644 tatcli/topic/truncate_tags.go create mode 100644 tatcli/ui/cmd.go create mode 100644 tatcli/ui/config.go create mode 100644 tatcli/ui/events.go create mode 100644 tatcli/ui/home.go create mode 100644 tatcli/ui/message.go create mode 100644 tatcli/ui/messages.go create mode 100644 tatcli/ui/result.go create mode 100644 tatcli/ui/send.go create mode 100644 tatcli/ui/topics.go create mode 100644 tatcli/ui/ui.go create mode 100644 tatcli/update/cmd.go create mode 100644 tatcli/user/add.go create mode 100644 tatcli/user/add_contact.go create mode 100644 tatcli/user/add_favorite_tag.go create mode 100644 tatcli/user/add_favorite_topic.go create mode 100644 tatcli/user/archive.go create mode 100644 tatcli/user/check.go create mode 100644 tatcli/user/contacts.go create mode 100644 tatcli/user/convert_to_system.go create mode 100644 tatcli/user/disable_notifications_all_topics.go create mode 100644 tatcli/user/disable_notifications_topic.go create mode 100644 tatcli/user/enable_notifications_all_topics.go create mode 100644 tatcli/user/enable_notifications_topic.go create mode 100644 tatcli/user/list.go create mode 100644 tatcli/user/me.go create mode 100644 tatcli/user/remove_contact.go create mode 100644 tatcli/user/remove_favorite_tag.go create mode 100644 tatcli/user/remove_favorite_topic.go create mode 100644 tatcli/user/rename.go create mode 100644 tatcli/user/reset.go create mode 100644 tatcli/user/set_admin.go create mode 100644 tatcli/user/system_reset.go create mode 100644 tatcli/user/update.go create mode 100644 tatcli/user/update_system.go create mode 100644 tatcli/user/user.go create mode 100644 tatcli/user/verify.go create mode 100644 tatcli/version/version.go rename vendor/github.com/{yesnault/hashtag => briandowns/spinner}/LICENSE (89%) create mode 100644 vendor/github.com/briandowns/spinner/README.md create mode 100644 vendor/github.com/briandowns/spinner/character_sets.go create mode 100644 vendor/github.com/briandowns/spinner/spinner.go delete mode 100644 vendor/github.com/eapache/go-resiliency/retrier/README.md delete mode 100644 vendor/github.com/eapache/go-resiliency/retrier/backoffs.go delete mode 100644 vendor/github.com/eapache/go-resiliency/retrier/classifier.go delete mode 100644 vendor/github.com/eapache/go-resiliency/retrier/retrier.go create mode 100644 vendor/github.com/fatih/color/LICENSE.md create mode 100644 vendor/github.com/fatih/color/README.md create mode 100644 vendor/github.com/fatih/color/color.go create mode 100644 vendor/github.com/fatih/color/doc.go create mode 100644 vendor/github.com/gin-gonic/gin/codecov.yml delete mode 100644 vendor/github.com/inconshreveable/mousetrap/LICENSE delete mode 100644 vendor/github.com/inconshreveable/mousetrap/README.md delete mode 100644 vendor/github.com/inconshreveable/mousetrap/trap_others.go delete mode 100644 vendor/github.com/inconshreveable/mousetrap/trap_windows.go delete mode 100644 vendor/github.com/inconshreveable/mousetrap/trap_windows_1.4.go delete mode 100644 vendor/github.com/kr/fs/LICENSE delete mode 100644 vendor/github.com/kr/fs/Readme delete mode 100644 vendor/github.com/kr/fs/filesystem.go delete mode 100644 vendor/github.com/kr/fs/walk.go create mode 100644 vendor/github.com/mattn/go-colorable/LICENSE create mode 100644 vendor/github.com/mattn/go-colorable/README.md create mode 100644 vendor/github.com/mattn/go-colorable/colorable_others.go create mode 100644 vendor/github.com/mattn/go-colorable/colorable_windows.go create mode 100644 vendor/github.com/mattn/go-colorable/noncolorable.go create mode 100644 vendor/github.com/mattn/go-isatty/LICENSE create mode 100644 vendor/github.com/mattn/go-isatty/README.md create mode 100644 vendor/github.com/mattn/go-isatty/doc.go create mode 100644 vendor/github.com/mattn/go-isatty/isatty_appengine.go create mode 100644 vendor/github.com/mattn/go-isatty/isatty_bsd.go create mode 100644 vendor/github.com/mattn/go-isatty/isatty_linux.go create mode 100644 vendor/github.com/mattn/go-isatty/isatty_solaris.go create mode 100644 vendor/github.com/mattn/go-isatty/isatty_windows.go create mode 100644 vendor/github.com/mattn/go-runewidth/LICENSE create mode 100644 vendor/github.com/mattn/go-runewidth/README.mkd create mode 100644 vendor/github.com/mattn/go-runewidth/runewidth.go create mode 100644 vendor/github.com/mattn/go-runewidth/runewidth_js.go create mode 100644 vendor/github.com/mattn/go-runewidth/runewidth_posix.go create mode 100644 vendor/github.com/mattn/go-runewidth/runewidth_windows.go delete mode 100644 vendor/github.com/mvdan/xurls/LICENSE delete mode 100644 vendor/github.com/mvdan/xurls/README.md delete mode 100644 vendor/github.com/mvdan/xurls/regex.go delete mode 100644 vendor/github.com/mvdan/xurls/schemes.go delete mode 100644 vendor/github.com/mvdan/xurls/tlds.go delete mode 100644 vendor/github.com/mvdan/xurls/tlds_pseudo.go delete mode 100644 vendor/github.com/mvdan/xurls/xurls.go create mode 100644 vendor/github.com/olekukonko/tablewriter/LICENCE.md create mode 100644 vendor/github.com/olekukonko/tablewriter/README.md create mode 100644 vendor/github.com/olekukonko/tablewriter/csv.go create mode 100644 vendor/github.com/olekukonko/tablewriter/table.go create mode 100644 vendor/github.com/olekukonko/tablewriter/test.csv create mode 100644 vendor/github.com/olekukonko/tablewriter/test_info.csv create mode 100644 vendor/github.com/olekukonko/tablewriter/util.go create mode 100644 vendor/github.com/olekukonko/tablewriter/wrap.go delete mode 100644 vendor/github.com/pkg/errors/LICENSE delete mode 100644 vendor/github.com/pkg/errors/README.md delete mode 100644 vendor/github.com/pkg/errors/appveyor.yml delete mode 100644 vendor/github.com/pkg/errors/errors.go delete mode 100644 vendor/github.com/pkg/errors/stack.go delete mode 100644 vendor/github.com/pkg/sftp/CONTRIBUTORS delete mode 100644 vendor/github.com/pkg/sftp/README.md delete mode 100644 vendor/github.com/pkg/sftp/attrs.go delete mode 100644 vendor/github.com/pkg/sftp/attrs_stubs.go delete mode 100644 vendor/github.com/pkg/sftp/attrs_unix.go delete mode 100644 vendor/github.com/pkg/sftp/client.go delete mode 100644 vendor/github.com/pkg/sftp/conn.go delete mode 100644 vendor/github.com/pkg/sftp/debug.go delete mode 100644 vendor/github.com/pkg/sftp/packet.go delete mode 100644 vendor/github.com/pkg/sftp/release.go delete mode 100644 vendor/github.com/pkg/sftp/server.go delete mode 100644 vendor/github.com/pkg/sftp/server_statvfs_darwin.go delete mode 100644 vendor/github.com/pkg/sftp/server_statvfs_impl.go delete mode 100644 vendor/github.com/pkg/sftp/server_statvfs_linux.go delete mode 100644 vendor/github.com/pkg/sftp/server_statvfs_stubs.go delete mode 100644 vendor/github.com/pkg/sftp/server_stubs.go delete mode 100644 vendor/github.com/pkg/sftp/server_unix.go delete mode 100644 vendor/github.com/pkg/sftp/sftp.go delete mode 100644 vendor/github.com/pmezard/go-difflib/LICENSE delete mode 100644 vendor/github.com/pmezard/go-difflib/difflib/difflib.go delete mode 100644 vendor/github.com/spf13/afero/sftp.go delete mode 100644 vendor/github.com/spf13/afero/sftp/file.go delete mode 100644 vendor/github.com/spf13/afero/sftp_test_go create mode 100644 vendor/github.com/spf13/jwalterweatherman/default_notepad.go create mode 100644 vendor/github.com/spf13/jwalterweatherman/log_counter.go create mode 100644 vendor/github.com/spf13/jwalterweatherman/notepad.go delete mode 100644 vendor/github.com/spf13/jwalterweatherman/thatswhyyoualwaysleaveanote.go delete mode 100644 vendor/github.com/stretchr/testify/LICENSE delete mode 100644 vendor/github.com/stretchr/testify/assert/assertion_forward.go delete mode 100644 vendor/github.com/stretchr/testify/assert/assertion_forward.go.tmpl delete mode 100644 vendor/github.com/stretchr/testify/assert/assertions.go delete mode 100644 vendor/github.com/stretchr/testify/assert/doc.go delete mode 100644 vendor/github.com/stretchr/testify/assert/errors.go delete mode 100644 vendor/github.com/stretchr/testify/assert/forward_assertions.go delete mode 100644 vendor/github.com/stretchr/testify/assert/http_assertions.go delete mode 100644 vendor/github.com/yesnault/hashtag/README.md delete mode 100644 vendor/github.com/yesnault/hashtag/hashtag.go delete mode 100644 vendor/github.com/yesnault/hashtag/tests.yml delete mode 100644 vendor/golang.org/x/crypto/LICENSE delete mode 100644 vendor/golang.org/x/crypto/PATENTS delete mode 100644 vendor/golang.org/x/crypto/curve25519/const_amd64.s delete mode 100644 vendor/golang.org/x/crypto/curve25519/cswap_amd64.s delete mode 100644 vendor/golang.org/x/crypto/curve25519/curve25519.go delete mode 100644 vendor/golang.org/x/crypto/curve25519/doc.go delete mode 100644 vendor/golang.org/x/crypto/curve25519/freeze_amd64.s delete mode 100644 vendor/golang.org/x/crypto/curve25519/ladderstep_amd64.s delete mode 100644 vendor/golang.org/x/crypto/curve25519/mont25519_amd64.go delete mode 100644 vendor/golang.org/x/crypto/curve25519/mul_amd64.s delete mode 100644 vendor/golang.org/x/crypto/curve25519/square_amd64.s delete mode 100644 vendor/golang.org/x/crypto/ed25519/ed25519.go delete mode 100644 vendor/golang.org/x/crypto/ed25519/internal/edwards25519/const.go delete mode 100644 vendor/golang.org/x/crypto/ed25519/internal/edwards25519/edwards25519.go delete mode 100644 vendor/golang.org/x/crypto/ssh/buffer.go delete mode 100644 vendor/golang.org/x/crypto/ssh/certs.go delete mode 100644 vendor/golang.org/x/crypto/ssh/channel.go delete mode 100644 vendor/golang.org/x/crypto/ssh/cipher.go delete mode 100644 vendor/golang.org/x/crypto/ssh/client.go delete mode 100644 vendor/golang.org/x/crypto/ssh/client_auth.go delete mode 100644 vendor/golang.org/x/crypto/ssh/common.go delete mode 100644 vendor/golang.org/x/crypto/ssh/connection.go delete mode 100644 vendor/golang.org/x/crypto/ssh/doc.go delete mode 100644 vendor/golang.org/x/crypto/ssh/handshake.go delete mode 100644 vendor/golang.org/x/crypto/ssh/kex.go delete mode 100644 vendor/golang.org/x/crypto/ssh/keys.go delete mode 100644 vendor/golang.org/x/crypto/ssh/mac.go delete mode 100644 vendor/golang.org/x/crypto/ssh/messages.go delete mode 100644 vendor/golang.org/x/crypto/ssh/mux.go delete mode 100644 vendor/golang.org/x/crypto/ssh/server.go delete mode 100644 vendor/golang.org/x/crypto/ssh/session.go delete mode 100644 vendor/golang.org/x/crypto/ssh/tcpip.go delete mode 100644 vendor/golang.org/x/crypto/ssh/transport.go create mode 100644 vendor/golang.org/x/sys/unix/asm_linux_mipsx.s create mode 100644 vendor/golang.org/x/sys/unix/syscall_linux_amd64_gc.go create mode 100644 vendor/golang.org/x/sys/unix/syscall_linux_mipsx.go create mode 100644 vendor/golang.org/x/sys/unix/syscall_unix_gc.go create mode 100644 vendor/golang.org/x/sys/unix/zerrors_linux_mips.go create mode 100644 vendor/golang.org/x/sys/unix/zerrors_linux_mipsle.go create mode 100644 vendor/golang.org/x/sys/unix/zsyscall_linux_mips.go create mode 100644 vendor/golang.org/x/sys/unix/zsyscall_linux_mipsle.go create mode 100644 vendor/golang.org/x/sys/unix/zsysnum_linux_mips.go create mode 100644 vendor/golang.org/x/sys/unix/zsysnum_linux_mipsle.go create mode 100644 vendor/golang.org/x/sys/unix/ztypes_linux_mips.go create mode 100644 vendor/golang.org/x/sys/unix/ztypes_linux_mipsle.go delete mode 100644 vendor/gopkg.in/bsm/ratelimit.v1/Makefile delete mode 100644 vendor/gopkg.in/bsm/ratelimit.v1/README.md delete mode 100644 vendor/gopkg.in/bsm/ratelimit.v1/ratelimit.go rename vendor/{github.com/pkg/sftp => gopkg.in/cheggaaa/pb.v1}/LICENSE (58%) create mode 100644 vendor/gopkg.in/cheggaaa/pb.v1/README.md create mode 100644 vendor/gopkg.in/cheggaaa/pb.v1/format.go create mode 100644 vendor/gopkg.in/cheggaaa/pb.v1/pb.go create mode 100644 vendor/gopkg.in/cheggaaa/pb.v1/pb_appengine.go create mode 100644 vendor/gopkg.in/cheggaaa/pb.v1/pb_nix.go create mode 100644 vendor/gopkg.in/cheggaaa/pb.v1/pb_solaris.go create mode 100644 vendor/gopkg.in/cheggaaa/pb.v1/pb_win.go create mode 100644 vendor/gopkg.in/cheggaaa/pb.v1/pb_x.go create mode 100644 vendor/gopkg.in/cheggaaa/pb.v1/pool.go create mode 100644 vendor/gopkg.in/cheggaaa/pb.v1/pool_win.go create mode 100644 vendor/gopkg.in/cheggaaa/pb.v1/pool_x.go create mode 100644 vendor/gopkg.in/cheggaaa/pb.v1/reader.go create mode 100644 vendor/gopkg.in/cheggaaa/pb.v1/runecount.go create mode 100644 vendor/gopkg.in/cheggaaa/pb.v1/termios_bsd.go create mode 100644 vendor/gopkg.in/cheggaaa/pb.v1/termios_nix.go delete mode 100644 vendor/gopkg.in/mgo.v2/LICENSE delete mode 100644 vendor/gopkg.in/mgo.v2/Makefile delete mode 100644 vendor/gopkg.in/mgo.v2/README.md delete mode 100644 vendor/gopkg.in/mgo.v2/auth.go delete mode 100644 vendor/gopkg.in/mgo.v2/bson/LICENSE delete mode 100644 vendor/gopkg.in/mgo.v2/bson/bson.go delete mode 100644 vendor/gopkg.in/mgo.v2/bson/decimal.go delete mode 100644 vendor/gopkg.in/mgo.v2/bson/decode.go delete mode 100644 vendor/gopkg.in/mgo.v2/bson/encode.go delete mode 100644 vendor/gopkg.in/mgo.v2/bson/json.go delete mode 100644 vendor/gopkg.in/mgo.v2/bulk.go delete mode 100644 vendor/gopkg.in/mgo.v2/cluster.go delete mode 100644 vendor/gopkg.in/mgo.v2/doc.go delete mode 100644 vendor/gopkg.in/mgo.v2/gridfs.go delete mode 100644 vendor/gopkg.in/mgo.v2/internal/json/LICENSE delete mode 100644 vendor/gopkg.in/mgo.v2/internal/json/decode.go delete mode 100644 vendor/gopkg.in/mgo.v2/internal/json/encode.go delete mode 100644 vendor/gopkg.in/mgo.v2/internal/json/extension.go delete mode 100644 vendor/gopkg.in/mgo.v2/internal/json/fold.go delete mode 100644 vendor/gopkg.in/mgo.v2/internal/json/indent.go delete mode 100644 vendor/gopkg.in/mgo.v2/internal/json/scanner.go delete mode 100644 vendor/gopkg.in/mgo.v2/internal/json/stream.go delete mode 100644 vendor/gopkg.in/mgo.v2/internal/json/tags.go delete mode 100644 vendor/gopkg.in/mgo.v2/internal/sasl/sasl.c delete mode 100644 vendor/gopkg.in/mgo.v2/internal/sasl/sasl.go delete mode 100644 vendor/gopkg.in/mgo.v2/internal/sasl/sasl_windows.c delete mode 100644 vendor/gopkg.in/mgo.v2/internal/sasl/sasl_windows.go delete mode 100644 vendor/gopkg.in/mgo.v2/internal/sasl/sasl_windows.h delete mode 100644 vendor/gopkg.in/mgo.v2/internal/sasl/sspi_windows.c delete mode 100644 vendor/gopkg.in/mgo.v2/internal/sasl/sspi_windows.h delete mode 100644 vendor/gopkg.in/mgo.v2/internal/scram/scram.go delete mode 100644 vendor/gopkg.in/mgo.v2/log.go delete mode 100644 vendor/gopkg.in/mgo.v2/queue.go delete mode 100644 vendor/gopkg.in/mgo.v2/raceoff.go delete mode 100644 vendor/gopkg.in/mgo.v2/raceon.go delete mode 100644 vendor/gopkg.in/mgo.v2/saslimpl.go delete mode 100644 vendor/gopkg.in/mgo.v2/saslstub.go delete mode 100644 vendor/gopkg.in/mgo.v2/server.go delete mode 100644 vendor/gopkg.in/mgo.v2/session.go delete mode 100644 vendor/gopkg.in/mgo.v2/socket.go delete mode 100644 vendor/gopkg.in/mgo.v2/stats.go delete mode 100644 vendor/gopkg.in/redis.v4/LICENSE delete mode 100644 vendor/gopkg.in/redis.v4/Makefile delete mode 100644 vendor/gopkg.in/redis.v4/README.md delete mode 100644 vendor/gopkg.in/redis.v4/cluster.go delete mode 100644 vendor/gopkg.in/redis.v4/command.go delete mode 100644 vendor/gopkg.in/redis.v4/commands.go delete mode 100644 vendor/gopkg.in/redis.v4/doc.go delete mode 100644 vendor/gopkg.in/redis.v4/internal/consistenthash/consistenthash.go delete mode 100644 vendor/gopkg.in/redis.v4/internal/errors/errors.go delete mode 100644 vendor/gopkg.in/redis.v4/internal/hashtag/hashtag.go delete mode 100644 vendor/gopkg.in/redis.v4/internal/log.go delete mode 100644 vendor/gopkg.in/redis.v4/internal/pool/conn.go delete mode 100644 vendor/gopkg.in/redis.v4/internal/pool/pool.go delete mode 100644 vendor/gopkg.in/redis.v4/internal/pool/pool_single.go delete mode 100644 vendor/gopkg.in/redis.v4/internal/pool/pool_sticky.go delete mode 100644 vendor/gopkg.in/redis.v4/internal/proto/proto.go delete mode 100644 vendor/gopkg.in/redis.v4/internal/proto/reader.go delete mode 100644 vendor/gopkg.in/redis.v4/internal/proto/writebuffer.go delete mode 100644 vendor/gopkg.in/redis.v4/internal/util.go delete mode 100644 vendor/gopkg.in/redis.v4/iterator.go delete mode 100644 vendor/gopkg.in/redis.v4/options.go delete mode 100644 vendor/gopkg.in/redis.v4/parser.go delete mode 100644 vendor/gopkg.in/redis.v4/pipeline.go delete mode 100644 vendor/gopkg.in/redis.v4/pubsub.go delete mode 100644 vendor/gopkg.in/redis.v4/redis.go delete mode 100644 vendor/gopkg.in/redis.v4/result.go delete mode 100644 vendor/gopkg.in/redis.v4/ring.go delete mode 100644 vendor/gopkg.in/redis.v4/script.go delete mode 100644 vendor/gopkg.in/redis.v4/sentinel.go delete mode 100644 vendor/gopkg.in/redis.v4/tx.go diff --git a/.travis.yml b/.travis.yml index 286a88b..e8cf31d 100644 --- a/.travis.yml +++ b/.travis.yml @@ -19,5 +19,14 @@ deploy: file: - api/bin/tat-darwin-amd64 - api/bin/tat-linux-amd64 + - tatcli/bin/tatcli-darwin-386 + - tatcli/bin/tatcli-darwin-amd64 + - tatcli/bin/tatcli-freebsd-386 + - tatcli/bin/tatcli-freebsd-amd64 + - tatcli/bin/tatcli-linux-386 + - tatcli/bin/tatcli-linux-amd64 + - tatcli/bin/tatcli-linux-arm + - tatcli/bin/tatcli-windows-386 + - tatcli/bin/tatcli-windows-amd64 on: tags: true diff --git a/docs/build/content/overview/architecture.md b/docs/build/content/overview/architecture.md index 32f053e..1628924 100644 --- a/docs/build/content/overview/architecture.md +++ b/docs/build/content/overview/architecture.md @@ -17,7 +17,7 @@ is component oriented, your can display messages with different Views. See [next more information. Source: [http://github.com/ovh/tatwebui](http://github.com/ovh/tatwebui) * Tatcli, the TAT Command Line Interface. All Tat features are available on tatcli. You can use it for "one shot" action on Tat Engine, or for display a UI in command line with `tatcli ui`. Tatcli ui -is popular to keep an eye on alerts or monitoring events without having a browser on it. Source: [http://github.com/ovh/tatcli](http://github.com/ovh/tatcli) +is popular to keep an eye on alerts or monitoring events without having a browser on it. Source: [http://github.com/ovh/tat/tatcli](http://github.com/ovh/tat/tatcli) * uServices: Tat Engine is simple to be used, it's also easy to develop uService above tat to make things a little more advanced, like on-call schedule & intervention, reporting, etc... You'll find some opensourced uService in chapter [Ecosystem](/ecosystem) diff --git a/docs/build/content/overview/contribute.md b/docs/build/content/overview/contribute.md index 894f708..05dea20 100644 --- a/docs/build/content/overview/contribute.md +++ b/docs/build/content/overview/contribute.md @@ -15,7 +15,7 @@ to hear from you! Make sure to read CONTRIBUTING file on repository concerned be ### Main Components * Tat Engine [Doc](/engine/) - [http://github.com/ovh/tat](http://github.com/ovh/tat) - [LICENSE](http://github.com/ovh/tat/blob/master/LICENSE) - [CONTRIBUTING](http://github.com/ovh/tat/blob/master/CONTRIBUTING.md) * Tatwebui [Doc](/tatwebui/) - [http://github.com/ovh/tatwebui](http://github.com/ovh/tatwebui) - [LICENSE](http://github.com/ovh/tatwebui/blob/master/LICENSE) - [CONTRIBUTING](http://github.com/ovh/tatwebui/blob/master/CONTRIBUTING.md) -* Tatcli [Doc](/tatcli/) - [http://github.com/ovh/tatcli](http://github.com/ovh/tatcli) - [LICENSE](http://github.com/ovh/tatcli/blob/master/LICENSE) - [CONTRIBUTING](http://github.com/ovh/tatcli/blob/master/CONTRIBUTING.md) +* Tatcli [Doc](/tatcli/) - [http://github.com/ovh/tat/tatcli](http://github.com/ovh/tat/tatcli) - [LICENSE](http://github.com/ovh/tat/tatcli/blob/master/LICENSE) - [CONTRIBUTING](http://github.com/ovh/tat/tatcli/blob/master/CONTRIBUTING.md) ### Views diff --git a/docs/build/content/overview/introduction.md b/docs/build/content/overview/introduction.md index b8234cc..baede34 100644 --- a/docs/build/content/overview/introduction.md +++ b/docs/build/content/overview/introduction.md @@ -17,7 +17,7 @@ Some use cases: - Team Communication & Reporting facilities ... -Tat Engine exposes only an HTTP REST API. You can manipulate this API with Tat Command Line Interface, aka tatcli, see https://github.com/ovh/tatcli. +Tat Engine exposes only an HTTP REST API. You can manipulate this API with Tat Command Line Interface, aka tatcli, see https://github.com/ovh/tat/tatcli. A WebUI is also available, see https://github.com/ovh/tatwebui. diff --git a/docs/build/content/sdk/golang-full-example.md b/docs/build/content/sdk/golang-full-example.md index fd76e3a..09d5973 100644 --- a/docs/build/content/sdk/golang-full-example.md +++ b/docs/build/content/sdk/golang-full-example.md @@ -125,4 +125,4 @@ func readConfig() { ## Notice You should split this file into many files. -See https://github.com/ovh/tatcli for CLI with many subcommands. +See https://github.com/ovh/tat/tatcli for CLI with many subcommands. diff --git a/docs/build/content/tatcli/general.md b/docs/build/content/tatcli/general.md index d71fcba..dd1b386 100644 --- a/docs/build/content/tatcli/general.md +++ b/docs/build/content/tatcli/general.md @@ -14,7 +14,7 @@ Tatcli, a Tat Command Line Interface. See Tat Engine for more information: https://github.com/ovh/tat ## Download -Download latest binary on release page https://github.com/ovh/tatcli/releases +Download latest binary on release page https://github.com/ovh/tat/tatcli/releases then `chmod +x tatcli` If you have already installed tatcli, you can update it with `tatcli update`. diff --git a/docs/build/static/json/search.json b/docs/build/static/json/search.json index 93e03fd..650747f 100644 --- a/docs/build/static/json/search.json +++ b/docs/build/static/json/search.json @@ -86,7 +86,7 @@ { "uri": "./tat/overview/architecture", "title": "Architecture", - "content": "---\ntitle: \"Architecture\"\nweight: 4\nprev: \"/overview/lifecycle\"\nnext: \"/overview/contribute\"\ntoc: false\n---\n\nMain components of a Tat Installation are:\n\nTat, also called Tat Engine. Your can running as many Engine as you want.\nYou can imagine running many Tat-Engine instances on Mesos/Marathon, Kubernetes or Swarm, or configure yourself behind a reverse proxy. Source: http://github.com/ovh/tat\nTatwebui: it's a web application, an easier way to call Tat Engine than curl. This application\nis component oriented, your can display messages with different Views. See next chapter about Tatwebui for\nmore information. Source: http://github.com/ovh/tatwebui\nTatcli, the TAT Command Line Interface. All Tat features are available on tatcli. You can use it\nfor \"one shot\" action on Tat Engine, or for display a UI in command line with tatcli ui. Tatcli ui\nis popular to keep an eye on alerts or monitoring events without having a browser on it. Source: http://github.com/ovh/tatcli\nuServices: Tat Engine is simple to be used, it's also easy to develop uService above tat to\nmake things a little more advanced, like on-call schedule & intervention, reporting, etc...\nYou'll find some opensourced uService in chapter Ecosystem\n", + "content": "---\ntitle: \"Architecture\"\nweight: 4\nprev: \"/overview/lifecycle\"\nnext: \"/overview/contribute\"\ntoc: false\n---\n\nMain components of a Tat Installation are:\n\nTat, also called Tat Engine. Your can running as many Engine as you want.\nYou can imagine running many Tat-Engine instances on Mesos/Marathon, Kubernetes or Swarm, or configure yourself behind a reverse proxy. Source: http://github.com/ovh/tat\nTatwebui: it's a web application, an easier way to call Tat Engine than curl. This application\nis component oriented, your can display messages with different Views. See next chapter about Tatwebui for\nmore information. Source: http://github.com/ovh/tatwebui\nTatcli, the TAT Command Line Interface. All Tat features are available on tatcli. You can use it\nfor \"one shot\" action on Tat Engine, or for display a UI in command line with tatcli ui. Tatcli ui\nis popular to keep an eye on alerts or monitoring events without having a browser on it. Source: http://github.com/ovh/tat/tatcli\nuServices: Tat Engine is simple to be used, it's also easy to develop uService above tat to\nmake things a little more advanced, like on-call schedule & intervention, reporting, etc...\nYou'll find some opensourced uService in chapter Ecosystem\n", "tags": [] }, { @@ -98,7 +98,7 @@ { "uri": "./tat/overview/contribute", "title": "Contribute", - "content": "---\ntitle: \"Contribute\"\nweight: 5\nprev: \"/overview/architecture\"\ntoc: true\n---\n\nContributing\n\nYou've developed a new cool feature? Fixed an annoying bug? We'd be happy\nto hear from you! Make sure to read CONTRIBUTING file on repository concerned before.\n\n Code\n\nMain Components\nTat Engine Doc - http://github.com/ovh/tat - LICENSE - CONTRIBUTING\nTatwebui Doc - http://github.com/ovh/tatwebui - LICENSE - CONTRIBUTING\nTatcli Doc - http://github.com/ovh/tatcli - LICENSE - CONTRIBUTING\n\n Views\n\nCDS View Doc - https://github.com/ovh/tatwebui-plugin-cdsview - LICENSE - CONTRIBUTING\nDashing View Doc - https://github.com/ovh/tatwebui-plugin-dashingview - LICENSE - CONTRIBUTING\nMonitoring View Doc - https://github.com/ovh/tatwebui-plugin-monitoringview - LICENSE - CONTRIBUTING\nNotifications View Doc - https://github.com/ovh/tatwebui-plugin-notificationsview - LICENSE - CONTRIBUTING\nPastat View Doc - https://github.com/ovh/tatwebui-plugin-pastatview - LICENSE - CONTRIBUTING\nRelease View Doc - https://github.com/ovh/tatwebui-plugin-releaseview - LICENSE - CONTRIBUTING\nStandard View Doc - https://github.com/ovh/tatwebui-plugin-standardview - LICENSE - CONTRIBUTING\n\nEcosystem\n\nAl2tat Doc - https://github.com/ovh/al2tat - LICENSE - CONTRIBUTING\nMail2tat Doc - https://github.com/ovh/mail2tat - LICENSE - CONTRIBUTING\nTat2XMPP Doc - https://github.com/ovh/tat2xmpp - LICENSE - CONTRIBUTING\n", + "content": "---\ntitle: \"Contribute\"\nweight: 5\nprev: \"/overview/architecture\"\ntoc: true\n---\n\nContributing\n\nYou've developed a new cool feature? Fixed an annoying bug? We'd be happy\nto hear from you! Make sure to read CONTRIBUTING file on repository concerned before.\n\n Code\n\nMain Components\nTat Engine Doc - http://github.com/ovh/tat - LICENSE - CONTRIBUTING\nTatwebui Doc - http://github.com/ovh/tatwebui - LICENSE - CONTRIBUTING\nTatcli Doc - http://github.com/ovh/tat/tatcli - LICENSE - CONTRIBUTING\n\n Views\n\nCDS View Doc - https://github.com/ovh/tatwebui-plugin-cdsview - LICENSE - CONTRIBUTING\nDashing View Doc - https://github.com/ovh/tatwebui-plugin-dashingview - LICENSE - CONTRIBUTING\nMonitoring View Doc - https://github.com/ovh/tatwebui-plugin-monitoringview - LICENSE - CONTRIBUTING\nNotifications View Doc - https://github.com/ovh/tatwebui-plugin-notificationsview - LICENSE - CONTRIBUTING\nPastat View Doc - https://github.com/ovh/tatwebui-plugin-pastatview - LICENSE - CONTRIBUTING\nRelease View Doc - https://github.com/ovh/tatwebui-plugin-releaseview - LICENSE - CONTRIBUTING\nStandard View Doc - https://github.com/ovh/tatwebui-plugin-standardview - LICENSE - CONTRIBUTING\n\nEcosystem\n\nAl2tat Doc - https://github.com/ovh/al2tat - LICENSE - CONTRIBUTING\nMail2tat Doc - https://github.com/ovh/mail2tat - LICENSE - CONTRIBUTING\nTat2XMPP Doc - https://github.com/ovh/tat2xmpp - LICENSE - CONTRIBUTING\n", "tags": [] }, { @@ -110,7 +110,7 @@ { "uri": "./tat/overview/introduction", "title": "Introduction", - "content": "---\ntitle: \"Introduction\"\nweight: 1\nprev: \"/overview\"\nnext: \"/overview/concepts\"\ntoc: false\n\n---\n\nTat, aka Text And Tags, is a communication tool - Human & Robot all together.\n\nSome use cases:\n\nViewing Pull Requests, Build And Deployment in one place\nAlerting & Monitoring Overview\nAgile view as simple as a whiteboard with post-it\nTeam Communication & Reporting facilities\n...\n\nTat Engine exposes only an HTTP REST API. You can manipulate this API with Tat Command Line Interface, aka tatcli, see https://github.com/ovh/tatcli.\n\nA WebUI is also available, see https://github.com/ovh/tatwebui.\n\nTat Engine:\n\nUses MongoDB as backend\nIs fully stateless, scale as you want\nIs the central Hub of Tat microservices ecosystem\n\nThe initial goal of TAT was to make an overview on Continuous Delivery Pipeline, with some pre-requisites:\n\nScalable, High Availability, Self-Hosted\nAPI, CLI\nSimple Usage\n\n", + "content": "---\ntitle: \"Introduction\"\nweight: 1\nprev: \"/overview\"\nnext: \"/overview/concepts\"\ntoc: false\n\n---\n\nTat, aka Text And Tags, is a communication tool - Human & Robot all together.\n\nSome use cases:\n\nViewing Pull Requests, Build And Deployment in one place\nAlerting & Monitoring Overview\nAgile view as simple as a whiteboard with post-it\nTeam Communication & Reporting facilities\n...\n\nTat Engine exposes only an HTTP REST API. You can manipulate this API with Tat Command Line Interface, aka tatcli, see https://github.com/ovh/tat/tatcli.\n\nA WebUI is also available, see https://github.com/ovh/tatwebui.\n\nTat Engine:\n\nUses MongoDB as backend\nIs fully stateless, scale as you want\nIs the central Hub of Tat microservices ecosystem\n\nThe initial goal of TAT was to make an overview on Continuous Delivery Pipeline, with some pre-requisites:\n\nScalable, High Availability, Self-Hosted\nAPI, CLI\nSimple Usage\n\n", "tags": [] }, { @@ -122,7 +122,7 @@ { "uri": "./tat/sdk/golang-full-example", "title": "Golang - Full Example", - "content": "---\ntitle: \"Golang - Full Example\"\nweight: 2\ntoc: true\nprev: \"/sdk/golang-simple-main\"\n\n---\n\nUsage\n\nThis example uses viper, cobra and tatcli config file.\n\nUsage:\n go build && ./mycli-full demo /YouTopic/subTopic your message\n\nwith a config file:\n go build && ./mycli-full --configFile $HOME/.tatcli/config.local.json demo /YouTopic/subTopic your message\n\n File main.go\n\npackage main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\n\tlog \"github.com/Sirupsen/logrus\"\n\t\"github.com/ovh/tat\"\n\t\"github.com/spf13/cobra\"\n\t\"github.com/spf13/viper\"\n)\n\nvar rootCmd = &cobra.Command{\n\tUse: \"mycli-full\",\n\tLong: SDK Use Demo,\n}\n\n// URL of tat engine, tat username and tat password\nvar (\n\thome = os.Getenv(\"HOME\")\n\ttaturl string\n\tusername string\n\tpassword string\n\n\t// ConfigFile is $HOME/.tatcli/config.json per default\n\t// contains user, password and url of tat\n\tconfigFile string\n)\n\nfunc main() {\n\taddCommands()\n\n\trootCmd.PersistentFlags().StringVarP(&taturl, \"url\", \"\", \"\", \"URL Tat Engine, facultative if you have a \"+home+\"/.tatcli/config.json file\")\n\trootCmd.PersistentFlags().StringVarP(&username, \"username\", \"u\", \"\", \"username, facultative if you have a \"+home+\"/.tatcli/config.json file\")\n\trootCmd.PersistentFlags().StringVarP(&password, \"password\", \"p\", \"\", \"password, facultative if you have a \"+home+\"/.tatcli/config.json file\")\n\trootCmd.PersistentFlags().StringVarP(&configFile, \"configFile\", \"c\", home+\"/.tatcli/config.json\", \"configuration file, default is \"+home+\"/.tatcli/config.json\")\n\n\tviper.BindPFlag(\"url\", rootCmd.PersistentFlags().Lookup(\"url\"))\n\tviper.BindPFlag(\"username\", rootCmd.PersistentFlags().Lookup(\"username\"))\n\tviper.BindPFlag(\"password\", rootCmd.PersistentFlags().Lookup(\"password\"))\n\n\tlog.SetLevel(log.DebugLevel)\n\n\tif err := rootCmd.Execute(); err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(-1)\n\t}\n}\n\n//AddCommands adds child commands to the root command rootCmd.\nfunc addCommands() {\n\trootCmd.AddCommand(cmdDemo)\n}\n\nvar cmdDemo = &cobra.Command{\n\tUse: \"demo topic msg\",\n\tShort: \"Demo Post Msg\",\n\tRun: func(cmd *cobra.Command, args []string) {\n\t\tcreate(args[0], args[1])\n\t},\n}\n\n// create creates a message in specified topic\nfunc create(topic, message string) {\n\treadConfig()\n\tm := tat.MessageJSON{Text: message, Topic: topic}\n\tmsgCreated, err := getClient().MessageAdd(m)\n\tif err != nil {\n\t\tlog.Errorf(\"Error:%s\", err)\n\t\treturn\n\t}\n\tlog.Debugf(\"ID Message Created: %d\", msgCreated.Message.ID)\n}\n\nfunc getClient() *tat.Client {\n\ttc, err := tat.NewClient(tat.Options{\n\t\tURL: viper.GetString(\"url\"),\n\t\tUsername: viper.GetString(\"username\"),\n\t\tPassword: viper.GetString(\"password\"),\n\t\tReferer: \"mycli.v0\",\n\t})\n\n\tif err != nil {\n\t\tlog.Fatalf(\"Error while create new Tat Client: %s\", err)\n\t}\n\n\ttat.DebugLogFunc = log.Debugf\n\treturn tc\n}\n\n// readConfig reads config in .tatcli/config per default\nfunc readConfig() {\n\tif configFile != \"\" {\n\t\tviper.SetConfigFile(configFile)\n\t\tviper.ReadInConfig() // Find and read the config file\n\t}\n}\n\nNotice\nYou should split this file into many files.\n\nSee https://github.com/ovh/tatcli for CLI with many subcommands.\n", + "content": "---\ntitle: \"Golang - Full Example\"\nweight: 2\ntoc: true\nprev: \"/sdk/golang-simple-main\"\n\n---\n\nUsage\n\nThis example uses viper, cobra and tatcli config file.\n\nUsage:\n go build && ./mycli-full demo /YouTopic/subTopic your message\n\nwith a config file:\n go build && ./mycli-full --configFile $HOME/.tatcli/config.local.json demo /YouTopic/subTopic your message\n\n File main.go\n\npackage main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\n\tlog \"github.com/Sirupsen/logrus\"\n\t\"github.com/ovh/tat\"\n\t\"github.com/spf13/cobra\"\n\t\"github.com/spf13/viper\"\n)\n\nvar rootCmd = &cobra.Command{\n\tUse: \"mycli-full\",\n\tLong: SDK Use Demo,\n}\n\n// URL of tat engine, tat username and tat password\nvar (\n\thome = os.Getenv(\"HOME\")\n\ttaturl string\n\tusername string\n\tpassword string\n\n\t// ConfigFile is $HOME/.tatcli/config.json per default\n\t// contains user, password and url of tat\n\tconfigFile string\n)\n\nfunc main() {\n\taddCommands()\n\n\trootCmd.PersistentFlags().StringVarP(&taturl, \"url\", \"\", \"\", \"URL Tat Engine, facultative if you have a \"+home+\"/.tatcli/config.json file\")\n\trootCmd.PersistentFlags().StringVarP(&username, \"username\", \"u\", \"\", \"username, facultative if you have a \"+home+\"/.tatcli/config.json file\")\n\trootCmd.PersistentFlags().StringVarP(&password, \"password\", \"p\", \"\", \"password, facultative if you have a \"+home+\"/.tatcli/config.json file\")\n\trootCmd.PersistentFlags().StringVarP(&configFile, \"configFile\", \"c\", home+\"/.tatcli/config.json\", \"configuration file, default is \"+home+\"/.tatcli/config.json\")\n\n\tviper.BindPFlag(\"url\", rootCmd.PersistentFlags().Lookup(\"url\"))\n\tviper.BindPFlag(\"username\", rootCmd.PersistentFlags().Lookup(\"username\"))\n\tviper.BindPFlag(\"password\", rootCmd.PersistentFlags().Lookup(\"password\"))\n\n\tlog.SetLevel(log.DebugLevel)\n\n\tif err := rootCmd.Execute(); err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(-1)\n\t}\n}\n\n//AddCommands adds child commands to the root command rootCmd.\nfunc addCommands() {\n\trootCmd.AddCommand(cmdDemo)\n}\n\nvar cmdDemo = &cobra.Command{\n\tUse: \"demo topic msg\",\n\tShort: \"Demo Post Msg\",\n\tRun: func(cmd *cobra.Command, args []string) {\n\t\tcreate(args[0], args[1])\n\t},\n}\n\n// create creates a message in specified topic\nfunc create(topic, message string) {\n\treadConfig()\n\tm := tat.MessageJSON{Text: message, Topic: topic}\n\tmsgCreated, err := getClient().MessageAdd(m)\n\tif err != nil {\n\t\tlog.Errorf(\"Error:%s\", err)\n\t\treturn\n\t}\n\tlog.Debugf(\"ID Message Created: %d\", msgCreated.Message.ID)\n}\n\nfunc getClient() *tat.Client {\n\ttc, err := tat.NewClient(tat.Options{\n\t\tURL: viper.GetString(\"url\"),\n\t\tUsername: viper.GetString(\"username\"),\n\t\tPassword: viper.GetString(\"password\"),\n\t\tReferer: \"mycli.v0\",\n\t})\n\n\tif err != nil {\n\t\tlog.Fatalf(\"Error while create new Tat Client: %s\", err)\n\t}\n\n\ttat.DebugLogFunc = log.Debugf\n\treturn tc\n}\n\n// readConfig reads config in .tatcli/config per default\nfunc readConfig() {\n\tif configFile != \"\" {\n\t\tviper.SetConfigFile(configFile)\n\t\tviper.ReadInConfig() // Find and read the config file\n\t}\n}\n\nNotice\nYou should split this file into many files.\n\nSee https://github.com/ovh/tat/tatcli for CLI with many subcommands.\n", "tags": [] }, { @@ -140,7 +140,7 @@ { "uri": "./tat/tatcli/general", "title": "General", - "content": "---\ntitle: \"General\"\nweight: 1\ntoc: true\nprev: \"/tatcli\"\nnext: \"/tatcli/tatcli-config\"\n\n---\n\nimg align=\"right\" src=\"https://raw.githubusercontent.com/ovh/tat/master/tat.png\"\n\nTatcli, a Tat Command Line Interface.\n\nSee Tat Engine for more information: https://github.com/ovh/tat\n\nDownload\nDownload latest binary on release page https://github.com/ovh/tatcli/releases\nthen chmod +x tatcli\n\nIf you have already installed tatcli, you can update it with tatcli update.\n\n Usage - General Rules\n\nA successful command will give you no feedback. If you want one, you can use -v argument.\nAfter each command, the exit code can be found in the $? variable. No error if exit code equals 0.\n", + "content": "---\ntitle: \"General\"\nweight: 1\ntoc: true\nprev: \"/tatcli\"\nnext: \"/tatcli/tatcli-config\"\n\n---\n\nimg align=\"right\" src=\"https://raw.githubusercontent.com/ovh/tat/master/tat.png\"\n\nTatcli, a Tat Command Line Interface.\n\nSee Tat Engine for more information: https://github.com/ovh/tat\n\nDownload\nDownload latest binary on release page https://github.com/ovh/tat/tatcli/releases\nthen chmod +x tatcli\n\nIf you have already installed tatcli, you can update it with tatcli update.\n\n Usage - General Rules\n\nA successful command will give you no feedback. If you want one, you can use -v argument.\nAfter each command, the exit code can be found in the $? variable. No error if exit code equals 0.\n", "tags": [] }, { diff --git a/docs/ecosystem/al2tat/index.html b/docs/ecosystem/al2tat/index.html index eb5fe85..70aafa4 100644 --- a/docs/ecosystem/al2tat/index.html +++ b/docs/ecosystem/al2tat/index.html @@ -3,7 +3,7 @@ - + diff --git a/docs/ecosystem/index.html b/docs/ecosystem/index.html index 840739e..a047009 100644 --- a/docs/ecosystem/index.html +++ b/docs/ecosystem/index.html @@ -3,7 +3,7 @@ - + diff --git a/docs/ecosystem/index.xml b/docs/ecosystem/index.xml index 8fa380c..4a61d9b 100644 --- a/docs/ecosystem/index.xml +++ b/docs/ecosystem/index.xml @@ -1,9 +1,9 @@ - Ecosystem-rsses on TAT - TextAndTag Documentation + Ecosystems on TAT - TextAndTag Documentation https://ovh.github.io/tat/ecosystem/index.xml - Recent content in Ecosystem-rsses on TAT - TextAndTag Documentation + Recent content in Ecosystems on TAT - TextAndTag Documentation Hugo -- gohugo.io en-us diff --git a/docs/ecosystem/mail2tat/index.html b/docs/ecosystem/mail2tat/index.html index 0926dd3..5ad84f6 100644 --- a/docs/ecosystem/mail2tat/index.html +++ b/docs/ecosystem/mail2tat/index.html @@ -3,7 +3,7 @@ - + diff --git a/docs/ecosystem/tat2es/index.html b/docs/ecosystem/tat2es/index.html index 4f32a31..596df55 100644 --- a/docs/ecosystem/tat2es/index.html +++ b/docs/ecosystem/tat2es/index.html @@ -3,7 +3,7 @@ - + diff --git a/docs/ecosystem/tat2xmpp/index.html b/docs/ecosystem/tat2xmpp/index.html index 72663cb..ba19371 100644 --- a/docs/ecosystem/tat2xmpp/index.html +++ b/docs/ecosystem/tat2xmpp/index.html @@ -3,7 +3,7 @@ - + diff --git a/docs/ecosystem/tatdashing/index.html b/docs/ecosystem/tatdashing/index.html index 9cb023b..6a2f09e 100644 --- a/docs/ecosystem/tatdashing/index.html +++ b/docs/ecosystem/tatdashing/index.html @@ -3,7 +3,7 @@ - + diff --git a/docs/engine/api-groups/index.html b/docs/engine/api-groups/index.html index 4dbab83..bdc6ed0 100644 --- a/docs/engine/api-groups/index.html +++ b/docs/engine/api-groups/index.html @@ -3,7 +3,7 @@ - + diff --git a/docs/engine/api-messages/index.html b/docs/engine/api-messages/index.html index e69c6cc..a3e38e5 100644 --- a/docs/engine/api-messages/index.html +++ b/docs/engine/api-messages/index.html @@ -3,7 +3,7 @@ - + diff --git a/docs/engine/api-presences/index.html b/docs/engine/api-presences/index.html index ddab88f..4e05318 100644 --- a/docs/engine/api-presences/index.html +++ b/docs/engine/api-presences/index.html @@ -3,7 +3,7 @@ - + diff --git a/docs/engine/api-system/index.html b/docs/engine/api-system/index.html index 7723dd7..f1ca234 100644 --- a/docs/engine/api-system/index.html +++ b/docs/engine/api-system/index.html @@ -3,7 +3,7 @@ - + diff --git a/docs/engine/api-topics/index.html b/docs/engine/api-topics/index.html index 03d3f96..c7243d9 100644 --- a/docs/engine/api-topics/index.html +++ b/docs/engine/api-topics/index.html @@ -3,7 +3,7 @@ - + @@ -1062,7 +1062,7 @@

Update param on one t -H "Content-Type: application/json" \ -H "Tat_username: admin" \ -H "Tat_password: passwordAdmin" \ - -d '{"topic": "/topicA", "recursive": "false", "maxlength": 140, "canForceDate": false, "canUpdateMsg": false, "canDeleteMsg": false, "canUpdateAllMsg": false, "canDeleteAllMsg": false, "adminCanUpdateAllMsg": false, "adminCanDeleteAllMsg": false}' \ + -d '{"topic": "/topicA", "recursive": "false", "maxlength": 140, "maxreplies": 30, "canForceDate": false, "canUpdateMsg": false, "canDeleteMsg": false, "canUpdateAllMsg": false, "canDeleteAllMsg": false, "adminCanUpdateAllMsg": false, "adminCanDeleteAllMsg": false}' \ https://<tatHostname>:<tatPort>/topic/param @@ -1074,7 +1074,7 @@

Update param on one t -H "Content-Type: application/json" \ -H "Tat_username: admin" \ -H "Tat_password: passwordAdmin" \ - -d '{"topic":"/Internal/Alerts","recursive":false,"maxlength":300,"canForceDate":false,"canUpdateMsg":false,"canDeleteMsg":true,"canUpdateAllMsg":false,"canDeleteAllMsg":false,"adminCanUpdateAllMsg":false,"adminCanDeleteAllMsg":false,"parameters":[{"key":"agileview","value":"qsdf#qsdf"},{"key":"tatwebui.view.default","value":"standardview-list"},{"key":"tatwebui.view.forced","value":""}]}' \ + -d '{"topic":"/Internal/Alerts","recursive":false,"maxlength":300,"maxreplies":30,"canForceDate":false,"canUpdateMsg":false,"canDeleteMsg":true,"canUpdateAllMsg":false,"canDeleteAllMsg":false,"adminCanUpdateAllMsg":false,"adminCanDeleteAllMsg":false,"parameters":[{"key":"agileview","value":"qsdf#qsdf"},{"key":"tatwebui.view.default","value":"standardview-list"},{"key":"tatwebui.view.forced","value":""}]}' \ https://<tatHostname>:<tatPort>/topic/param diff --git a/docs/engine/api-users/index.html b/docs/engine/api-users/index.html index 4914c24..4ef3ec0 100644 --- a/docs/engine/api-users/index.html +++ b/docs/engine/api-users/index.html @@ -3,7 +3,7 @@ - + diff --git a/docs/engine/general/index.html b/docs/engine/general/index.html index bb02fdb..5ee9f70 100644 --- a/docs/engine/general/index.html +++ b/docs/engine/general/index.html @@ -3,7 +3,7 @@ - + diff --git a/docs/engine/index.html b/docs/engine/index.html index 495757c..af3de52 100644 --- a/docs/engine/index.html +++ b/docs/engine/index.html @@ -3,7 +3,7 @@ - + diff --git a/docs/engine/index.xml b/docs/engine/index.xml index 4859489..f195130 100644 --- a/docs/engine/index.xml +++ b/docs/engine/index.xml @@ -1,9 +1,9 @@ - Engine-rsses on TAT - TextAndTag Documentation + Engines on TAT - TextAndTag Documentation https://ovh.github.io/tat/engine/index.xml - Recent content in Engine-rsses on TAT - TextAndTag Documentation + Recent content in Engines on TAT - TextAndTag Documentation Hugo -- gohugo.io en-us @@ -1035,7 +1035,7 @@ curl -XGET https://&lt;tatHostname&gt;:&lt;tatPort&gt;/topics?sk -H &quot;Content-Type: application/json&quot; \ -H &quot;Tat_username: admin&quot; \ -H &quot;Tat_password: passwordAdmin&quot; \ - -d '{&quot;topic&quot;: &quot;/topicA&quot;, &quot;recursive&quot;: &quot;false&quot;, &quot;maxlength&quot;: 140, &quot;canForceDate&quot;: false, &quot;canUpdateMsg&quot;: false, &quot;canDeleteMsg&quot;: false, &quot;canUpdateAllMsg&quot;: false, &quot;canDeleteAllMsg&quot;: false, &quot;adminCanUpdateAllMsg&quot;: false, &quot;adminCanDeleteAllMsg&quot;: false}' \ + -d '{&quot;topic&quot;: &quot;/topicA&quot;, &quot;recursive&quot;: &quot;false&quot;, &quot;maxlength&quot;: 140, &quot;maxreplies&quot;: 30, &quot;canForceDate&quot;: false, &quot;canUpdateMsg&quot;: false, &quot;canDeleteMsg&quot;: false, &quot;canUpdateAllMsg&quot;: false, &quot;canDeleteAllMsg&quot;: false, &quot;adminCanUpdateAllMsg&quot;: false, &quot;adminCanDeleteAllMsg&quot;: false}' \ https://&lt;tatHostname&gt;:&lt;tatPort&gt;/topic/param </code></pre> @@ -1047,7 +1047,7 @@ curl -XGET https://&lt;tatHostname&gt;:&lt;tatPort&gt;/topics?sk -H &quot;Content-Type: application/json&quot; \ -H &quot;Tat_username: admin&quot; \ -H &quot;Tat_password: passwordAdmin&quot; \ - -d '{&quot;topic&quot;:&quot;/Internal/Alerts&quot;,&quot;recursive&quot;:false,&quot;maxlength&quot;:300,&quot;canForceDate&quot;:false,&quot;canUpdateMsg&quot;:false,&quot;canDeleteMsg&quot;:true,&quot;canUpdateAllMsg&quot;:false,&quot;canDeleteAllMsg&quot;:false,&quot;adminCanUpdateAllMsg&quot;:false,&quot;adminCanDeleteAllMsg&quot;:false,&quot;parameters&quot;:[{&quot;key&quot;:&quot;agileview&quot;,&quot;value&quot;:&quot;qsdf#qsdf&quot;},{&quot;key&quot;:&quot;tatwebui.view.default&quot;,&quot;value&quot;:&quot;standardview-list&quot;},{&quot;key&quot;:&quot;tatwebui.view.forced&quot;,&quot;value&quot;:&quot;&quot;}]}' \ + -d '{&quot;topic&quot;:&quot;/Internal/Alerts&quot;,&quot;recursive&quot;:false,&quot;maxlength&quot;:300,&quot;maxreplies&quot;:30,&quot;canForceDate&quot;:false,&quot;canUpdateMsg&quot;:false,&quot;canDeleteMsg&quot;:true,&quot;canUpdateAllMsg&quot;:false,&quot;canDeleteAllMsg&quot;:false,&quot;adminCanUpdateAllMsg&quot;:false,&quot;adminCanDeleteAllMsg&quot;:false,&quot;parameters&quot;:[{&quot;key&quot;:&quot;agileview&quot;,&quot;value&quot;:&quot;qsdf#qsdf&quot;},{&quot;key&quot;:&quot;tatwebui.view.default&quot;,&quot;value&quot;:&quot;standardview-list&quot;},{&quot;key&quot;:&quot;tatwebui.view.forced&quot;,&quot;value&quot;:&quot;&quot;}]}' \ https://&lt;tatHostname&gt;:&lt;tatPort&gt;/topic/param </code></pre> diff --git a/docs/engine/production-installation/index.html b/docs/engine/production-installation/index.html index 18b2adb..3d9155a 100644 --- a/docs/engine/production-installation/index.html +++ b/docs/engine/production-installation/index.html @@ -3,7 +3,7 @@ - + diff --git a/docs/engine/simple-installation/index.html b/docs/engine/simple-installation/index.html index 56a7e87..85e109f 100644 --- a/docs/engine/simple-installation/index.html +++ b/docs/engine/simple-installation/index.html @@ -3,7 +3,7 @@ - + diff --git a/docs/index.html b/docs/index.html index da93a43..e7eb26a 100644 --- a/docs/index.html +++ b/docs/index.html @@ -1,7 +1,7 @@ - + diff --git a/docs/index.xml b/docs/index.xml index 4246e79..78dc155 100644 --- a/docs/index.xml +++ b/docs/index.xml @@ -8,100 +8,6 @@ en-us - - Ecosystem - https://ovh.github.io/tat/ecosystem/ - Mon, 01 Jan 0001 00:00:00 +0000 - - https://ovh.github.io/tat/ecosystem/ - - -<h3 id="chapter-6">Chapter 6</h3> - -<h1 id="ecosystem">Ecosystem</h1> - - - - - Overview - https://ovh.github.io/tat/overview/ - Mon, 01 Jan 0001 00:00:00 +0000 - - https://ovh.github.io/tat/overview/ - - -<h3 id="chapter-1">Chapter 1</h3> - -<h1 id="tat-overview">TAT Overview</h1> - -<p>Discover what is Tat and the core-concepts behind it.</p> - - - - - Tat CLI Reference - https://ovh.github.io/tat/tatcli/ - Mon, 01 Jan 0001 00:00:00 +0000 - - https://ovh.github.io/tat/tatcli/ - - -<h3 id="chapter-4">Chapter 4</h3> - -<h1 id="tatcli">TATCLI</h1> - -<p>Reference</p> - - - - - Tat Engine Reference - https://ovh.github.io/tat/engine/ - Mon, 01 Jan 0001 00:00:00 +0000 - - https://ovh.github.io/tat/engine/ - - -<h3 id="chapter-3">Chapter 3</h3> - -<h1 id="tat-engine">Tat Engine</h1> - -<p>Reference</p> - - - - - Tat SDK - https://ovh.github.io/tat/sdk/ - Mon, 01 Jan 0001 00:00:00 +0000 - - https://ovh.github.io/tat/sdk/ - - -<h3 id="chapter-5">Chapter 5</h3> - -<h1 id="overview">Overview</h1> - -<p>TAT SDK</p> - -<p><a href="https://godoc.org/github.com/ovh/tat#Client">Godoc</a></p> - - - - - Tat Webui - https://ovh.github.io/tat/tatwebui/ - Mon, 01 Jan 0001 00:00:00 +0000 - - https://ovh.github.io/tat/tatwebui/ - - -<h3 id="chapter-2">Chapter 2</h3> - -<h1 id="tat-webui">Tat Webui</h1> - - - General https://ovh.github.io/tat/engine/general/ @@ -338,7 +244,7 @@ Tat Engine communicates only with JSON format with its API, even for messages se <h2 id="download">Download</h2> -<p>Download latest binary on release page <a href="https://github.com/ovh/tatcli/releases">https://github.com/ovh/tatcli/releases</a> +<p>Download latest binary on release page <a href="https://github.com/ovh/tat/tatcli/releases">https://github.com/ovh/tat/tatcli/releases</a> then <code>chmod +x tatcli</code></p> <p>If you have already installed tatcli, you can update it with <code>tatcli update</code>.</p> @@ -448,7 +354,7 @@ Please check next chapter <a href="../golang-full-example">&ld &hellip;</li> </ul> -<p>Tat Engine exposes only an HTTP REST API. You can manipulate this API with Tat Command Line Interface, aka tatcli, see <a href="https://github.com/ovh/tatcli">https://github.com/ovh/tatcli</a>.</p> +<p>Tat Engine exposes only an HTTP REST API. You can manipulate this API with Tat Command Line Interface, aka tatcli, see <a href="https://github.com/ovh/tat/tatcli">https://github.com/ovh/tat/tatcli</a>.</p> <p>A WebUI is also available, see <a href="https://github.com/ovh/tatwebui">https://github.com/ovh/tatwebui</a>.</p> @@ -1430,7 +1336,640 @@ func readConfig() { <p>You should split this file into many files.</p> -<p>See <a href="https://github.com/ovh/tatcli">https://github.com/ovh/tatcli</a> for CLI with many subcommands.</p> +<p>See <a href="https://github.com/ovh/tat/tatcli">https://github.com/ovh/tat/tatcli</a> for CLI with many subcommands.</p> + + + + + Standard View + https://ovh.github.io/tat/tatwebui/standardview/ + Mon, 01 Jan 0001 00:00:00 +0000 + + https://ovh.github.io/tat/tatwebui/standardview/ + + +<h2 id="screenshots">Screenshots</h2> + +<h3 id="messages-list">Messages - List</h3> + +<p><img src="https://ovh.github.io/tat/imgs/tatwebui-standard-view-list.png?width=80%" alt="Standard View" /></p> + +<h3 id="messages-edit">Messages - Edit</h3> + +<p><img src="https://ovh.github.io/tat/imgs/tatwebui-standard-view-details.png?width=80%" alt="Standard View" /></p> + +<h2 id="configuration">Configuration</h2> + +<p>In plugin.tpl.json file, add this line :</p> + +<pre><code>&quot;tatwebui-plugin-standardview&quot;: &quot;git+https://github.com/ovh/tatwebui-plugin-standardview.git&quot; +</code></pre> + +<h2 id="source">Source</h2> + +<p><a href="https://github.com/ovh/tatwebui-plugin-standardview">https://github.com/ovh/tatwebui-plugin-standardview</a></p> + + + + + mail2tat + https://ovh.github.io/tat/ecosystem/mail2tat/ + Mon, 01 Jan 0001 00:00:00 +0000 + + https://ovh.github.io/tat/ecosystem/mail2tat/ + + +<p>Create a message on Tat by sending a mail. Mail2tat check an imap account +and create a message for each mail received.</p> + +<h2 id="tat-configuration">Tat Configuration</h2> + +<ul> +<li>Add Read Write to user tat.system.mail on your destination topic</li> +<li>Check option : &ldquo;System User can force dateCreation of message ?&rdquo;</li> +</ul> + +<h2 id="simple-usage">Simple usage</h2> + +<p>Send a mail to tat@your-domain with</p> + +<pre><code>subjet : &lt;topicName&gt; +Body : text of message +</code></pre> + +<p>Example of subject : <code>/Internal/YourTopic</code></p> + +<h2 id="thread-on-tat">Thread on Tat</h2> + +<p>Send a mail to tat@your-domain with :</p> + +<pre><code>subjet : &lt;topicName&gt;,&lt;idGroup&gt; +Body: text of message +</code></pre> + +<p>Example of subject: <code>/Internal/YourTopic,something</code></p> + +<h2 id="faq">FAQ</h2> + +<p>Time between sending mail and post on tat ? Each minute : check mail and send on tat. +Restriction on From ? Yes, see arg : only @your-domain. All mail received from another domain are not send on tat.</p> + +<h2 id="usage">Usage</h2> + +<h3 id="building">Building</h3> + +<pre><code class="language-bash">mkdir -p $GOPATH/src/github.com/ovh +cd $GOPATH/src/github.com/ovh +git clone git@github.com:ovh/tat-contrib.git +cd tat-contrib/mail2tat/api +go build +./api -h +</code></pre> + +<h3 id="flags">Flags</h3> + +<pre><code>./api -h +MAIL2TAT - Mail to Tat + +Usage: + mail2tat [flags] + +Flags: + --activate-cron Activate Cron (default true) + --imap-host string IMAP Host + --imap-password string IMAP Password + --imap-username string IMAP Username + --listen-port string RunKPI Listen Port (default &quot;8084&quot;) + --log-level string Log Level : debug, info or warn + --password-tat-engine string Password Tat Engine + --production Production mode + --url-tat-engine string URL Tat Engine (default &quot;http://localhost:8080&quot;) + --username-tat-engine string Username Tat Engine +</code></pre> + + + + + tatcli config -h + https://ovh.github.io/tat/tatcli/tatcli-config/ + Mon, 01 Jan 0001 00:00:00 +0000 + + https://ovh.github.io/tat/tatcli/tatcli-config/ + + +<h2 id="command-description">Command Description</h2> + +<h3 id="tatcli-config-h">tatcli config -h</h3> + +<pre><code>Config commands: tatcli config &lt;command&gt; + +Usage: + tatcli config [command] + +Aliases: + config, c + + +Available Commands: + template Write a template configuration file in $HOME/.tatcli/config.json: tatcli config template + show Show Configuration: tatcli config show + +Flags: + -h, --help=false: help for config + +Global Flags: see tatcli -h + +Use &quot;tatcli config [command] --help&quot; for more information about a command. + +</code></pre> + +<h2 id="example">Example</h2> + +<h3 id="credentials">Credentials</h3> + +<p>Config file is under $HOME/.tatcli/config.json +You can create it with this command:</p> + +<pre><code class="language-bash">tatcli config template +</code></pre> + +<p>Template is:</p> + +<pre><code>{ + &quot;username&quot;:&quot;myUsername&quot;, + &quot;password&quot;:&quot;myPassword&quot;, + &quot;url&quot;:&quot;http://urltat:port&quot; +} +</code></pre> + + + + + API - Topics + https://ovh.github.io/tat/engine/api-topics/ + Mon, 01 Jan 0001 00:00:00 +0000 + + https://ovh.github.io/tat/engine/api-topics/ + + +<h2 id="create-a-topic">Create a Topic</h2> + +<p>Rules:</p> + +<ul> +<li>User can create a root topic if he is a Tat Admin.</li> +<li>User can create topics under <code>/Private/username/</code></li> +<li>User can create topics if he is an admin on the Parent Topic or belong to an admin group on the Parent topic. +Example: Create /AAA/BBB: Parent Topic is /AAA</li> +</ul> + +<pre><code class="language-bash">curl -XPOST \ + -H &quot;Content-Type: application/json&quot; \ + -H &quot;Tat_username: admin&quot; \ + -H &quot;Tat_password: passwordAdmin&quot; \ + -d '{&quot;topic&quot;: &quot;/topicA&quot;, &quot;description&quot;: &quot;Topic Description&quot;}' \ + https://&lt;tatHostname&gt;:&lt;tatPort&gt;/topic +</code></pre> + +<h2 id="delete-a-topic">Delete a topic</h2> + +<pre><code class="language-bash">curl -XDELETE \ + -H &quot;Content-Type: application/json&quot; \ + -H &quot;Tat_username: admin&quot; \ + -H &quot;Tat_password: passwordAdmin&quot; \ + https://&lt;tatHostname&gt;:&lt;tatPort&gt;/topic/subtopic +</code></pre> + +<h2 id="truncate-a-topic">Truncate a topic</h2> + +<p>Only for Tat Admin and administrators on topic.</p> + +<pre><code class="language-bash">curl -XPUT \ + -H &quot;Content-Type: application/json&quot; \ + -H &quot;Tat_username: admin&quot; \ + -H &quot;Tat_password: passwordAdmin&quot; \ + -d '{&quot;topic&quot;: &quot;/topicA&quot;}' \ + https://&lt;tatHostname&gt;:&lt;tatPort&gt;/topic/truncate +</code></pre> + +<h2 id="compute-tags-on-a-topic">Compute tags on a topic</h2> + +<p>Only for Tat Admin and administrators on topic.</p> + +<p>Set &ldquo;tags&rdquo; attribute on topic, with an array of all tags used in this topic. +One entry in &ldquo;tags&rdquo; attribute per text of tag.</p> + +<p>Topic&rsquo;s tags are showed with : +GET https://<tatHostname>:<tatPort>/topic/topicName</p> + +<pre><code class="language-bash">curl -XPUT \ + -H &quot;Content-Type: application/json&quot; \ + -H &quot;Tat_username: admin&quot; \ + -H &quot;Tat_password: passwordAdmin&quot; \ + -d '{&quot;topic&quot;: &quot;/topicA&quot;}' \ + https://&lt;tatHostname&gt;:&lt;tatPort&gt;/topic/compute/tags +</code></pre> + +<p>Example of usage of tags attribute: autocompletion of tag on UI when written new message on a topic</p> + +<h2 id="compute-labels-on-a-topic">Compute labels on a topic</h2> + +<p>Only for Tat Admin and administrators on topic.</p> + +<p>Set &ldquo;labels&rdquo; attribute on topic, with an array of all labels used in this topic. +One entry in &ldquo;labels&rdquo; attribute per text &amp; color of label.</p> + +<p>Topic&rsquo;s labels are showed with : +GET https://<tatHostname>:<tatPort>/topic/topicName</p> + +<pre><code class="language-bash">curl -XPUT \ + -H &quot;Content-Type: application/json&quot; \ + -H &quot;Tat_username: admin&quot; \ + -H &quot;Tat_password: passwordAdmin&quot; \ + -d '{&quot;topic&quot;: &quot;/topicA&quot;}' \ + https://&lt;tatHostname&gt;:&lt;tatPort&gt;/topic/compute/labels +</code></pre> + +<p>Example of usage of labels attribute: label autocompletion on UI when adding new label</p> + +<h2 id="compute-tags-on-all-topics">Compute tags on all topics</h2> + +<p>Only for Tat Admin.</p> + +<pre><code class="language-bash">curl -XPUT \ + -H &quot;Content-Type: application/json&quot; \ + -H &quot;Tat_username: admin&quot; \ + -H &quot;Tat_password: passwordAdmin&quot; \ + https://&lt;tatHostname&gt;:&lt;tatPort&gt;/topics/compute/tags +</code></pre> + +<h2 id="compute-labels-on-all-topics">Compute labels on all topics</h2> + +<p>Only for Tat Admin.</p> + +<pre><code class="language-bash">curl -XPUT \ + -H &quot;Content-Type: application/json&quot; \ + -H &quot;Tat_username: admin&quot; \ + -H &quot;Tat_password: passwordAdmin&quot; \ + https://&lt;tatHostname&gt;:&lt;tatPort&gt;/topics/compute/labels +</code></pre> + +<h2 id="set-a-param-on-all-topics">Set a param on all topics</h2> + +<p>Only for Tat Admin and for attributes isAutoComputeTags and isAutoComputeLabels.</p> + +<pre><code class="language-bash">curl -XPUT \ + -H &quot;Content-Type: application/json&quot; \ + -H &quot;Tat_username: admin&quot; \ + -H &quot;Tat_password: passwordAdmin&quot; \ + -d '{&quot;paramName&quot;:&quot;isAutoComputeLabels&quot;,&quot;paramValue&quot;:&quot;false&quot;}' \ + https://&lt;tatHostname&gt;:&lt;tatPort&gt;/topics/param +</code></pre> + +<h2 id="truncate-cached-tags-on-a-topic">Truncate cached tags on a topic</h2> + +<p>Only for Tat Admin and administrators on topic.</p> + +<p>Truncate &ldquo;tags&rdquo; attribute on topic.</p> + +<pre><code class="language-bash">curl -XPUT \ + -H &quot;Content-Type: application/json&quot; \ + -H &quot;Tat_username: admin&quot; \ + -H &quot;Tat_password: passwordAdmin&quot; \ + -d '{&quot;topic&quot;: &quot;/topicA&quot;}' \ + https://&lt;tatHostname&gt;:&lt;tatPort&gt;/topic/tags/truncate +</code></pre> + +<h2 id="truncate-cached-labels-on-a-topic">Truncate cached labels on a topic</h2> + +<p>Only for Tat Admin and administrators on topic.</p> + +<p>Truncate &ldquo;labels&rdquo; attribute on topic.</p> + +<pre><code class="language-bash">curl -XPUT \ + -H &quot;Content-Type: application/json&quot; \ + -H &quot;Tat_username: admin&quot; \ + -H &quot;Tat_password: passwordAdmin&quot; \ + -d '{&quot;topic&quot;: &quot;/topicA&quot;}' \ + https://&lt;tatHostname&gt;:&lt;tatPort&gt;/topic/labels/truncate +</code></pre> + +<h2 id="getting-one-topic">Getting one Topic</h2> + +<pre><code class="language-bash">curl -XGET https://&lt;tatHostname&gt;:&lt;tatPort&gt;/topic/topicName | python -m json.tool +curl -XGET https://&lt;tatHostname&gt;:&lt;tatPort&gt;/topic/topicName/subTopic | python -m json.tool +</code></pre> + +<h2 id="getting-topics-list">Getting Topics List</h2> + +<pre><code class="language-bash">curl -XGET https://&lt;tatHostname&gt;:&lt;tatPort&gt;/topics?skip=&lt;skip&gt;&amp;limit=&lt;limit&gt; | python -m json.tool +curl -XGET https://&lt;tatHostname&gt;:&lt;tatPort&gt;/topics?skip=&lt;skip&gt;&amp;limit=&lt;limit&gt;&amp;argName=valName&amp;arg2Name=val2Name | python -m json.tool +</code></pre> + +<h3 id="parameters">Parameters</h3> + +<ul> +<li>skip: Skip skips over the n initial documents from the query results</li> +<li>limit: Limit restricts the maximum number of documents retrieved</li> +<li>topic: Topic name, example: /topicA</li> +<li>topicPath: Topic start path, example: /topicA will return /topicA/subA, /topicA/subB</li> +<li>idTopic: id of topic</li> +<li>description: description of topic</li> +<li>dateMinCreation: filter result on dateCreation, timestamp Unix format</li> +<li>dateMaxCreation: filter result on dateCreation, timestamp Unix Format</li> +<li>getNbMsgUnread: if true, add new array to return, topicsMsgUnread with topic:flag. flag can be -1 if unknown, 0 or 1 if there is one or more messages unread</li> +<li>onlyFavorites: if true, return only favorites topics, except /Private/*. All privates topics are returned.</li> +<li>getForTatAdmin: if true, and requester is a Tat Admin, returns all topics (except /Private/*) without checking user access</li> +</ul> + +<h3 id="example">Example</h3> + +<pre><code class="language-bash">curl -XGET https://&lt;tatHostname&gt;:&lt;tatPort&gt;/topics?skip=0&amp;limit=100 | python -m json.tool +</code></pre> + +<h2 id="add-a-parameter-to-a-topic">Add a parameter to a topic</h2> + +<p>For admin of topic or on <code>/Private/username/*</code></p> + +<pre><code class="language-bash">curl -XPUT \ + -H &quot;Content-Type: application/json&quot; \ + -H &quot;Tat_username: admin&quot; \ + -H &quot;Tat_password: passwordAdmin&quot; \ + -d '{&quot;topic&quot;: &quot;/topicA&quot;, &quot;key&quot;: &quot;keyOfParameter&quot;, &quot;value&quot;: &quot;valueOfParameter&quot;, &quot;recursive&quot;: &quot;false&quot;}' \ + https://&lt;tatHostname&gt;:&lt;tatPort&gt;/topic/add/parameter +</code></pre> + +<h2 id="remove-a-parameter-to-a-topic">Remove a parameter to a topic</h2> + +<pre><code class="language-bash">curl -XPUT \ + -H &quot;Content-Type: application/json&quot; \ + -H &quot;Tat_username: admin&quot; \ + -H &quot;Tat_password: passwordAdmin&quot; \ + -d '{&quot;topic&quot;: &quot;/topicA&quot;, &quot;key&quot;: &quot;keyOfParameter&quot;, &quot;recursive&quot;: &quot;false&quot;}' \ + https://&lt;tatHostname&gt;:&lt;tatPort&gt;/topic/remove/parameter +</code></pre> + +<h2 id="add-a-read-only-user-to-a-topic">Add a read only user to a topic</h2> + +<pre><code class="language-bash">curl -XPUT \ + -H &quot;Content-Type: application/json&quot; \ + -H &quot;Tat_username: admin&quot; \ + -H &quot;Tat_password: passwordAdmin&quot; \ + -d '{&quot;topic&quot;: &quot;/topicA&quot;, &quot;username&quot;: &quot;usernameToAdd&quot;, &quot;recursive&quot;: &quot;false&quot;}' \ + https://&lt;tatHostname&gt;:&lt;tatPort&gt;/topic/add/rouser +</code></pre> + +<h2 id="add-a-read-write-user-to-a-topic">Add a read write user to a topic</h2> + +<pre><code class="language-bash">curl -XPUT \ + -H &quot;Content-Type: application/json&quot; \ + -H &quot;Tat_username: admin&quot; \ + -H &quot;Tat_password: passwordAdmin&quot; \ + -d '{&quot;topic&quot;: &quot;/topicA&quot;, &quot;username&quot;: &quot;usernameToAdd&quot;, &quot;recursive&quot;: &quot;false&quot;}' \ + https://&lt;tatHostname&gt;:&lt;tatPort&gt;/topic/add/rwuser +</code></pre> + +<h2 id="add-an-admin-user-to-a-topic">Add an admin user to a topic</h2> + +<pre><code class="language-bash">curl -XPUT \ + -H &quot;Content-Type: application/json&quot; \ + -H &quot;Tat_username: admin&quot; \ + -H &quot;Tat_password: passwordAdmin&quot; \ + -d '{&quot;topic&quot;: &quot;/topicA&quot;, &quot;username&quot;: &quot;usernameToAdd&quot;, &quot;recursive&quot;: &quot;false&quot;}' \ + https://&lt;tatHostname&gt;:&lt;tatPort&gt;/topic/add/adminuser +</code></pre> + +<h2 id="delete-a-read-only-user-from-a-topic">Delete a read only user from a topic</h2> + +<pre><code class="language-bash">curl -XPUT \ + -H &quot;Content-Type: application/json&quot; \ + -H &quot;Tat_username: admin&quot; \ + -H &quot;Tat_password: passwordAdmin&quot; \ + -d '{&quot;topic&quot;: &quot;/topicA&quot;, &quot;username&quot;: &quot;usernameToRemove&quot;, &quot;recursive&quot;: &quot;false&quot;}' \ + https://&lt;tatHostname&gt;:&lt;tatPort&gt;/topic/remove/rouser +</code></pre> + +<h2 id="delete-a-read-write-user-from-a-topic">Delete a read write user from a topic</h2> + +<pre><code class="language-bash">curl -XPUT \ + -H &quot;Content-Type: application/json&quot; \ + -H &quot;Tat_username: admin&quot; \ + -H &quot;Tat_password: passwordAdmin&quot; \ + -d '{&quot;topic&quot;: &quot;/topicA&quot;, &quot;username&quot;: &quot;usernameToRemove&quot;, &quot;recursive&quot;: &quot;false&quot;}' \ + https://&lt;tatHostname&gt;:&lt;tatPort&gt;/topic/remove/wuser +</code></pre> + +<h2 id="delete-an-admin-user-from-a-topic">Delete an admin user from a topic</h2> + +<pre><code class="language-bash">curl -XPUT \ + -H &quot;Content-Type: application/json&quot; \ + -H &quot;Tat_username: admin&quot; \ + -H &quot;Tat_password: passwordAdmin&quot; \ + -d '{&quot;topic&quot;: &quot;/topicA&quot;, &quot;username&quot;: &quot;usernameToRemove&quot;, &quot;recursive&quot;: &quot;false&quot;}' \ + https://&lt;tatHostname&gt;:&lt;tatPort&gt;/topic/remove/adminuser +</code></pre> + +<h2 id="add-a-read-only-group-to-a-topic">Add a read only group to a topic</h2> + +<pre><code class="language-bash">curl -XPUT \ + -H &quot;Content-Type: application/json&quot; \ + -H &quot;Tat_username: admin&quot; \ + -H &quot;Tat_password: passwordAdmin&quot; \ + -d '{&quot;topic&quot;: &quot;/topicA&quot;, &quot;groupname&quot;: &quot;groupnameToAdd&quot;, &quot;recursive&quot;: &quot;false&quot;}' \ + https://&lt;tatHostname&gt;:&lt;tatPort&gt;/topic/add/rogroup +</code></pre> + +<h2 id="add-a-read-write-group-to-a-topic">Add a read write group to a topic</h2> + +<pre><code class="language-bash">curl -XPUT \ + -H &quot;Content-Type: application/json&quot; \ + -H &quot;Tat_username: admin&quot; \ + -H &quot;Tat_password: passwordAdmin&quot; \ + -d '{&quot;topic&quot;: &quot;/topicA&quot;, &quot;groupname&quot;: &quot;groupnameToAdd&quot;, &quot;recursive&quot;: &quot;false&quot;}' \ + https://&lt;tatHostname&gt;:&lt;tatPort&gt;/topic/add/rwgroup +</code></pre> + +<h2 id="add-an-admin-group-to-a-topic">Add an admin group to a topic</h2> + +<pre><code class="language-bash">curl -XPUT \ + -H &quot;Content-Type: application/json&quot; \ + -H &quot;Tat_username: admin&quot; \ + -H &quot;Tat_password: passwordAdmin&quot; \ + -d '{&quot;topic&quot;: &quot;/topicA&quot;, &quot;groupname&quot;: &quot;groupnameToAdd&quot;, &quot;recursive&quot;: &quot;false&quot;}' \ + https://&lt;tatHostname&gt;:&lt;tatPort&gt;/topic/add/admingroup +</code></pre> + +<h2 id="delete-a-read-only-group-from-a-topic">Delete a read only group from a topic</h2> + +<pre><code class="language-bash">curl -XPUT \ + -H &quot;Content-Type: application/json&quot; \ + -H &quot;Tat_username: admin&quot; \ + -H &quot;Tat_password: passwordAdmin&quot; \ + -d '{&quot;topic&quot;: &quot;/topicA&quot;, &quot;groupname&quot;: &quot;groupnameToRemove&quot;, &quot;recursive&quot;: &quot;false&quot;}' \ + https://&lt;tatHostname&gt;:&lt;tatPort&gt;/topic/remove/rogroup +</code></pre> + +<h2 id="delete-a-read-write-group-from-a-topic">Delete a read write group from a topic</h2> + +<pre><code class="language-bash">curl -XPUT \ + -H &quot;Content-Type: application/json&quot; \ + -H &quot;Tat_username: admin&quot; \ + -H &quot;Tat_password: passwordAdmin&quot; \ + -d '{&quot;topic&quot;: &quot;/topicA&quot;, &quot;groupname&quot;: &quot;groupnameToRemove&quot;, &quot;recursive&quot;: &quot;false&quot;}' \ + https://&lt;tatHostname&gt;:&lt;tatPort&gt;/topic/remove/rwgroup +</code></pre> + +<h2 id="delete-an-admin-group-from-a-topic">Delete an admin group from a topic</h2> + +<pre><code class="language-bash">curl -XPUT \ + -H &quot;Content-Type: application/json&quot; \ + -H &quot;Tat_username: admin&quot; \ + -H &quot;Tat_password: passwordAdmin&quot; \ + -d '{&quot;topic&quot;: &quot;/topicA&quot;, &quot;groupname&quot;: &quot;groupnameToRemove&quot;, &quot;recursive&quot;: &quot;false&quot;}' \ + https://&lt;tatHostname&gt;:&lt;tatPort&gt;/topic/remove/rwgroup +</code></pre> + +<h2 id="update-param-on-one-topic-admin-or-admin-on-topic">Update param on one topic: admin or admin on topic</h2> + +<pre><code class="language-bash">curl -XPUT \ + -H &quot;Content-Type: application/json&quot; \ + -H &quot;Tat_username: admin&quot; \ + -H &quot;Tat_password: passwordAdmin&quot; \ + -d '{&quot;topic&quot;: &quot;/topicA&quot;, &quot;recursive&quot;: &quot;false&quot;, &quot;maxlength&quot;: 140, &quot;maxreplies&quot;: 30, &quot;canForceDate&quot;: false, &quot;canUpdateMsg&quot;: false, &quot;canDeleteMsg&quot;: false, &quot;canUpdateAllMsg&quot;: false, &quot;canDeleteAllMsg&quot;: false, &quot;adminCanUpdateAllMsg&quot;: false, &quot;adminCanDeleteAllMsg&quot;: false}' \ + https://&lt;tatHostname&gt;:&lt;tatPort&gt;/topic/param +</code></pre> + +<p>Parameters key is optional.</p> + +<p>Example with key parameters :</p> + +<pre><code class="language-bash">curl -XPUT \ + -H &quot;Content-Type: application/json&quot; \ + -H &quot;Tat_username: admin&quot; \ + -H &quot;Tat_password: passwordAdmin&quot; \ + -d '{&quot;topic&quot;:&quot;/Internal/Alerts&quot;,&quot;recursive&quot;:false,&quot;maxlength&quot;:300,&quot;maxreplies&quot;:30,&quot;canForceDate&quot;:false,&quot;canUpdateMsg&quot;:false,&quot;canDeleteMsg&quot;:true,&quot;canUpdateAllMsg&quot;:false,&quot;canDeleteAllMsg&quot;:false,&quot;adminCanUpdateAllMsg&quot;:false,&quot;adminCanDeleteAllMsg&quot;:false,&quot;parameters&quot;:[{&quot;key&quot;:&quot;agileview&quot;,&quot;value&quot;:&quot;qsdf#qsdf&quot;},{&quot;key&quot;:&quot;tatwebui.view.default&quot;,&quot;value&quot;:&quot;standardview-list&quot;},{&quot;key&quot;:&quot;tatwebui.view.forced&quot;,&quot;value&quot;:&quot;&quot;}]}' \ + https://&lt;tatHostname&gt;:&lt;tatPort&gt;/topic/param +</code></pre> + + + + + DevOps LifeCycle / Feedback Loop + https://ovh.github.io/tat/overview/lifecycle/ + Mon, 01 Jan 0001 00:00:00 +0000 + + https://ovh.github.io/tat/overview/lifecycle/ + + +<p><img src="https://ovh.github.io/tat/imgs/devops-lifecycle.png?width=50%" alt="DevOps LifeCycle" /></p> + +<h2 id="feedback-everywhere">Feedback everywhere</h2> + +<p>We want feedback, not only when applications are in production, but everywhere. +PullRequest, build, Release, Monitoring, etc&hellip;</p> + +<p>Following examples show how we are using Tat through our DevOps lifecycle @ OVH.</p> + +<p>First of all, TaT was designed to be a hub of all Continuous Delivery and DevOps communcation. By plugin all the software running in Plug all the software running in your DevOps ecosystem to Tat, you&rsquo;ll be able to follow all the things in TaT and improve as well team and machines collaboration]</p> + +<pre><code>Plan : + +Code : + +Build And Tests : + +Release : + +Monitor : +</code></pre> + +<h2 id="plan">Plan</h2> + +<p>Starting the DevOps lifcycle with an agile view designed to plan your next release/iteration</p> + +<p><img src="https://ovh.github.io/tat/imgs/devops-lifecycle-plan.png?width=250px" alt="DevOps LifeCycle Plan" /> +<img src="https://ovh.github.io/tat/imgs/devops-lifecycle-plan-agile.png?width=750px" alt="DevOps LifeCycle Plan" /> +<img src="https://ovh.github.io/tat/imgs/devops-lifecycle-plan-roadmap.png?width=750px" alt="DevOps LifeCycle Plan" /></p> + +<h2 id="code">Code</h2> + +<p>Follow Pull Request, and share pieces of Code</p> + +<p><img src="https://ovh.github.io/tat/imgs/devops-lifecycle-code.png?width=250px" alt="DevOps LifeCycle Code" /> +<img src="https://ovh.github.io/tat/imgs/devops-lifecycle-code-gist.png?width=750px" alt="DevOps LifeCycle Code" /> +<img src="https://ovh.github.io/tat/imgs/devops-lifecycle-code-pull-request.png?width=750px" alt="DevOps LifeCycle Code" /></p> + +<h2 id="build-test">Build &amp; Test</h2> + +<p>Follow Continuous Integration, Continuous Delivery Pipelines through a pipeline views. Here shown with CDS (lien vers CDS).</p> + +<p><img src="https://ovh.github.io/tat/imgs/devops-lifecycle-build.png?width=250px" alt="DevOps LifeCycle Build" /> +<img src="https://ovh.github.io/tat/imgs/devops-lifecycle-build-cds.png?width=750px" alt="DevOps LifeCycle Build" /></p> + +<h2 id="release">Release</h2> + +<p>End of your cycle commitment: build automatically your release note from your git repository, JIRA &hellip;</p> + +<p><img src="https://ovh.github.io/tat/imgs/devops-lifecycle-release.png?width=250px" alt="DevOps LifeCycle Release" /> +<img src="https://ovh.github.io/tat/imgs/devops-lifecycle-release-changelog-1.png?width=750px" alt="DevOps LifeCycle Release" /> +<img src="https://ovh.github.io/tat/imgs/devops-lifecycle-release-changelog-2.png?width=750px" alt="DevOps LifeCycle Release" /></p> + +<h2 id="deploy">Deploy</h2> + +<p><img src="https://ovh.github.io/tat/imgs/devops-lifecycle-deploy.png?width=250px" alt="DevOps LifeCycle Deploy" /> +<img src="https://ovh.github.io/tat/imgs/devops-lifecycle-build-cds.png?width=750px" alt="DevOps LifeCycle Deploy" /></p> + +<h2 id="monitor">Monitor</h2> + +<p>Build your own dashing view, monitor things with a light Terminal UI, showing resources heatmap of planning your interventions..</p> + +<p><img src="https://ovh.github.io/tat/imgs/devops-lifecycle-monitor.png?width=250px" alt="DevOps LifeCycle Monitor" /> +<img src="https://ovh.github.io/tat/imgs/devops-lifecycle-monitor-dashboard.png?width=750px" alt="DevOps LifeCycle Monitor" /> +<img src="https://ovh.github.io/tat/imgs/devops-lifecycle-monitor-tatcli.png?width=750px" alt="DevOps LifeCycle Monitor" /> +<img src="https://ovh.github.io/tat/imgs/devops-lifecycle-monitor-multiple.png?width=750px" alt="DevOps LifeCycle Monitor" /> +<img src="https://ovh.github.io/tat/imgs/devops-lifecycle-monitor-oncall.png?width=750px" alt="DevOps LifeCycle Monitor" /></p> + +<h2 id="feedback">Feedback</h2> + +<p><img src="https://ovh.github.io/tat/imgs/devops-lifecycle-feedback.png?width=250px" alt="DevOps LifeCycle Feedback" /> +<img src="https://ovh.github.io/tat/imgs/devops-lifecycle-feedback-kpi.png?width=750px" alt="DevOps LifeCycle Feedback" /></p> + + + + + Notifications View + https://ovh.github.io/tat/tatwebui/notificationsview/ + Mon, 01 Jan 0001 00:00:00 +0000 + + https://ovh.github.io/tat/tatwebui/notificationsview/ + + +<p>When a message contains a mention for someone, a other message is created by Tat Engine in topic +/Private/username/Notifications, where username is the user mentioned.</p> + +<p>Example :</p> + +<ul> +<li>a message &ldquo;a first notification for @yesnault&rdquo; in topic /Internal/App</li> +<li>a other message &ldquo;and a second @yesnault in topic /Internal/App&rdquo; in topic /Internal/App</li> +</ul> + +<p>see result in screenshot below for these two messages in topic /Private/yesnault/Notifications</p> + +<h2 id="screenshot">Screenshot</h2> + +<p><img src="https://ovh.github.io/tat/imgs/tatwebui-notifications-view.png?width=80%" alt="Notifications View" /></p> + +<h2 id="configuration">Configuration</h2> + +<p>In plugin.tpl.json file, add this line :</p> + +<pre><code>&quot;tatwebui-plugin-notificationsview&quot;: &quot;git+https://github.com/ovh/tatwebui-plugin-notificationsview.git&quot; +</code></pre> + +<h2 id="source">Source</h2> + +<p><a href="https://github.com/ovh/tatwebui-plugin-notificationsview">https://github.com/ovh/tatwebui-plugin-notificationsview</a></p> diff --git a/docs/json/search.json b/docs/json/search.json index 93e03fd..650747f 100644 --- a/docs/json/search.json +++ b/docs/json/search.json @@ -86,7 +86,7 @@ { "uri": "./tat/overview/architecture", "title": "Architecture", - "content": "---\ntitle: \"Architecture\"\nweight: 4\nprev: \"/overview/lifecycle\"\nnext: \"/overview/contribute\"\ntoc: false\n---\n\nMain components of a Tat Installation are:\n\nTat, also called Tat Engine. Your can running as many Engine as you want.\nYou can imagine running many Tat-Engine instances on Mesos/Marathon, Kubernetes or Swarm, or configure yourself behind a reverse proxy. Source: http://github.com/ovh/tat\nTatwebui: it's a web application, an easier way to call Tat Engine than curl. This application\nis component oriented, your can display messages with different Views. See next chapter about Tatwebui for\nmore information. Source: http://github.com/ovh/tatwebui\nTatcli, the TAT Command Line Interface. All Tat features are available on tatcli. You can use it\nfor \"one shot\" action on Tat Engine, or for display a UI in command line with tatcli ui. Tatcli ui\nis popular to keep an eye on alerts or monitoring events without having a browser on it. Source: http://github.com/ovh/tatcli\nuServices: Tat Engine is simple to be used, it's also easy to develop uService above tat to\nmake things a little more advanced, like on-call schedule & intervention, reporting, etc...\nYou'll find some opensourced uService in chapter Ecosystem\n", + "content": "---\ntitle: \"Architecture\"\nweight: 4\nprev: \"/overview/lifecycle\"\nnext: \"/overview/contribute\"\ntoc: false\n---\n\nMain components of a Tat Installation are:\n\nTat, also called Tat Engine. Your can running as many Engine as you want.\nYou can imagine running many Tat-Engine instances on Mesos/Marathon, Kubernetes or Swarm, or configure yourself behind a reverse proxy. Source: http://github.com/ovh/tat\nTatwebui: it's a web application, an easier way to call Tat Engine than curl. This application\nis component oriented, your can display messages with different Views. See next chapter about Tatwebui for\nmore information. Source: http://github.com/ovh/tatwebui\nTatcli, the TAT Command Line Interface. All Tat features are available on tatcli. You can use it\nfor \"one shot\" action on Tat Engine, or for display a UI in command line with tatcli ui. Tatcli ui\nis popular to keep an eye on alerts or monitoring events without having a browser on it. Source: http://github.com/ovh/tat/tatcli\nuServices: Tat Engine is simple to be used, it's also easy to develop uService above tat to\nmake things a little more advanced, like on-call schedule & intervention, reporting, etc...\nYou'll find some opensourced uService in chapter Ecosystem\n", "tags": [] }, { @@ -98,7 +98,7 @@ { "uri": "./tat/overview/contribute", "title": "Contribute", - "content": "---\ntitle: \"Contribute\"\nweight: 5\nprev: \"/overview/architecture\"\ntoc: true\n---\n\nContributing\n\nYou've developed a new cool feature? Fixed an annoying bug? We'd be happy\nto hear from you! Make sure to read CONTRIBUTING file on repository concerned before.\n\n Code\n\nMain Components\nTat Engine Doc - http://github.com/ovh/tat - LICENSE - CONTRIBUTING\nTatwebui Doc - http://github.com/ovh/tatwebui - LICENSE - CONTRIBUTING\nTatcli Doc - http://github.com/ovh/tatcli - LICENSE - CONTRIBUTING\n\n Views\n\nCDS View Doc - https://github.com/ovh/tatwebui-plugin-cdsview - LICENSE - CONTRIBUTING\nDashing View Doc - https://github.com/ovh/tatwebui-plugin-dashingview - LICENSE - CONTRIBUTING\nMonitoring View Doc - https://github.com/ovh/tatwebui-plugin-monitoringview - LICENSE - CONTRIBUTING\nNotifications View Doc - https://github.com/ovh/tatwebui-plugin-notificationsview - LICENSE - CONTRIBUTING\nPastat View Doc - https://github.com/ovh/tatwebui-plugin-pastatview - LICENSE - CONTRIBUTING\nRelease View Doc - https://github.com/ovh/tatwebui-plugin-releaseview - LICENSE - CONTRIBUTING\nStandard View Doc - https://github.com/ovh/tatwebui-plugin-standardview - LICENSE - CONTRIBUTING\n\nEcosystem\n\nAl2tat Doc - https://github.com/ovh/al2tat - LICENSE - CONTRIBUTING\nMail2tat Doc - https://github.com/ovh/mail2tat - LICENSE - CONTRIBUTING\nTat2XMPP Doc - https://github.com/ovh/tat2xmpp - LICENSE - CONTRIBUTING\n", + "content": "---\ntitle: \"Contribute\"\nweight: 5\nprev: \"/overview/architecture\"\ntoc: true\n---\n\nContributing\n\nYou've developed a new cool feature? Fixed an annoying bug? We'd be happy\nto hear from you! Make sure to read CONTRIBUTING file on repository concerned before.\n\n Code\n\nMain Components\nTat Engine Doc - http://github.com/ovh/tat - LICENSE - CONTRIBUTING\nTatwebui Doc - http://github.com/ovh/tatwebui - LICENSE - CONTRIBUTING\nTatcli Doc - http://github.com/ovh/tat/tatcli - LICENSE - CONTRIBUTING\n\n Views\n\nCDS View Doc - https://github.com/ovh/tatwebui-plugin-cdsview - LICENSE - CONTRIBUTING\nDashing View Doc - https://github.com/ovh/tatwebui-plugin-dashingview - LICENSE - CONTRIBUTING\nMonitoring View Doc - https://github.com/ovh/tatwebui-plugin-monitoringview - LICENSE - CONTRIBUTING\nNotifications View Doc - https://github.com/ovh/tatwebui-plugin-notificationsview - LICENSE - CONTRIBUTING\nPastat View Doc - https://github.com/ovh/tatwebui-plugin-pastatview - LICENSE - CONTRIBUTING\nRelease View Doc - https://github.com/ovh/tatwebui-plugin-releaseview - LICENSE - CONTRIBUTING\nStandard View Doc - https://github.com/ovh/tatwebui-plugin-standardview - LICENSE - CONTRIBUTING\n\nEcosystem\n\nAl2tat Doc - https://github.com/ovh/al2tat - LICENSE - CONTRIBUTING\nMail2tat Doc - https://github.com/ovh/mail2tat - LICENSE - CONTRIBUTING\nTat2XMPP Doc - https://github.com/ovh/tat2xmpp - LICENSE - CONTRIBUTING\n", "tags": [] }, { @@ -110,7 +110,7 @@ { "uri": "./tat/overview/introduction", "title": "Introduction", - "content": "---\ntitle: \"Introduction\"\nweight: 1\nprev: \"/overview\"\nnext: \"/overview/concepts\"\ntoc: false\n\n---\n\nTat, aka Text And Tags, is a communication tool - Human & Robot all together.\n\nSome use cases:\n\nViewing Pull Requests, Build And Deployment in one place\nAlerting & Monitoring Overview\nAgile view as simple as a whiteboard with post-it\nTeam Communication & Reporting facilities\n...\n\nTat Engine exposes only an HTTP REST API. You can manipulate this API with Tat Command Line Interface, aka tatcli, see https://github.com/ovh/tatcli.\n\nA WebUI is also available, see https://github.com/ovh/tatwebui.\n\nTat Engine:\n\nUses MongoDB as backend\nIs fully stateless, scale as you want\nIs the central Hub of Tat microservices ecosystem\n\nThe initial goal of TAT was to make an overview on Continuous Delivery Pipeline, with some pre-requisites:\n\nScalable, High Availability, Self-Hosted\nAPI, CLI\nSimple Usage\n\n", + "content": "---\ntitle: \"Introduction\"\nweight: 1\nprev: \"/overview\"\nnext: \"/overview/concepts\"\ntoc: false\n\n---\n\nTat, aka Text And Tags, is a communication tool - Human & Robot all together.\n\nSome use cases:\n\nViewing Pull Requests, Build And Deployment in one place\nAlerting & Monitoring Overview\nAgile view as simple as a whiteboard with post-it\nTeam Communication & Reporting facilities\n...\n\nTat Engine exposes only an HTTP REST API. You can manipulate this API with Tat Command Line Interface, aka tatcli, see https://github.com/ovh/tat/tatcli.\n\nA WebUI is also available, see https://github.com/ovh/tatwebui.\n\nTat Engine:\n\nUses MongoDB as backend\nIs fully stateless, scale as you want\nIs the central Hub of Tat microservices ecosystem\n\nThe initial goal of TAT was to make an overview on Continuous Delivery Pipeline, with some pre-requisites:\n\nScalable, High Availability, Self-Hosted\nAPI, CLI\nSimple Usage\n\n", "tags": [] }, { @@ -122,7 +122,7 @@ { "uri": "./tat/sdk/golang-full-example", "title": "Golang - Full Example", - "content": "---\ntitle: \"Golang - Full Example\"\nweight: 2\ntoc: true\nprev: \"/sdk/golang-simple-main\"\n\n---\n\nUsage\n\nThis example uses viper, cobra and tatcli config file.\n\nUsage:\n go build && ./mycli-full demo /YouTopic/subTopic your message\n\nwith a config file:\n go build && ./mycli-full --configFile $HOME/.tatcli/config.local.json demo /YouTopic/subTopic your message\n\n File main.go\n\npackage main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\n\tlog \"github.com/Sirupsen/logrus\"\n\t\"github.com/ovh/tat\"\n\t\"github.com/spf13/cobra\"\n\t\"github.com/spf13/viper\"\n)\n\nvar rootCmd = &cobra.Command{\n\tUse: \"mycli-full\",\n\tLong: SDK Use Demo,\n}\n\n// URL of tat engine, tat username and tat password\nvar (\n\thome = os.Getenv(\"HOME\")\n\ttaturl string\n\tusername string\n\tpassword string\n\n\t// ConfigFile is $HOME/.tatcli/config.json per default\n\t// contains user, password and url of tat\n\tconfigFile string\n)\n\nfunc main() {\n\taddCommands()\n\n\trootCmd.PersistentFlags().StringVarP(&taturl, \"url\", \"\", \"\", \"URL Tat Engine, facultative if you have a \"+home+\"/.tatcli/config.json file\")\n\trootCmd.PersistentFlags().StringVarP(&username, \"username\", \"u\", \"\", \"username, facultative if you have a \"+home+\"/.tatcli/config.json file\")\n\trootCmd.PersistentFlags().StringVarP(&password, \"password\", \"p\", \"\", \"password, facultative if you have a \"+home+\"/.tatcli/config.json file\")\n\trootCmd.PersistentFlags().StringVarP(&configFile, \"configFile\", \"c\", home+\"/.tatcli/config.json\", \"configuration file, default is \"+home+\"/.tatcli/config.json\")\n\n\tviper.BindPFlag(\"url\", rootCmd.PersistentFlags().Lookup(\"url\"))\n\tviper.BindPFlag(\"username\", rootCmd.PersistentFlags().Lookup(\"username\"))\n\tviper.BindPFlag(\"password\", rootCmd.PersistentFlags().Lookup(\"password\"))\n\n\tlog.SetLevel(log.DebugLevel)\n\n\tif err := rootCmd.Execute(); err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(-1)\n\t}\n}\n\n//AddCommands adds child commands to the root command rootCmd.\nfunc addCommands() {\n\trootCmd.AddCommand(cmdDemo)\n}\n\nvar cmdDemo = &cobra.Command{\n\tUse: \"demo topic msg\",\n\tShort: \"Demo Post Msg\",\n\tRun: func(cmd *cobra.Command, args []string) {\n\t\tcreate(args[0], args[1])\n\t},\n}\n\n// create creates a message in specified topic\nfunc create(topic, message string) {\n\treadConfig()\n\tm := tat.MessageJSON{Text: message, Topic: topic}\n\tmsgCreated, err := getClient().MessageAdd(m)\n\tif err != nil {\n\t\tlog.Errorf(\"Error:%s\", err)\n\t\treturn\n\t}\n\tlog.Debugf(\"ID Message Created: %d\", msgCreated.Message.ID)\n}\n\nfunc getClient() *tat.Client {\n\ttc, err := tat.NewClient(tat.Options{\n\t\tURL: viper.GetString(\"url\"),\n\t\tUsername: viper.GetString(\"username\"),\n\t\tPassword: viper.GetString(\"password\"),\n\t\tReferer: \"mycli.v0\",\n\t})\n\n\tif err != nil {\n\t\tlog.Fatalf(\"Error while create new Tat Client: %s\", err)\n\t}\n\n\ttat.DebugLogFunc = log.Debugf\n\treturn tc\n}\n\n// readConfig reads config in .tatcli/config per default\nfunc readConfig() {\n\tif configFile != \"\" {\n\t\tviper.SetConfigFile(configFile)\n\t\tviper.ReadInConfig() // Find and read the config file\n\t}\n}\n\nNotice\nYou should split this file into many files.\n\nSee https://github.com/ovh/tatcli for CLI with many subcommands.\n", + "content": "---\ntitle: \"Golang - Full Example\"\nweight: 2\ntoc: true\nprev: \"/sdk/golang-simple-main\"\n\n---\n\nUsage\n\nThis example uses viper, cobra and tatcli config file.\n\nUsage:\n go build && ./mycli-full demo /YouTopic/subTopic your message\n\nwith a config file:\n go build && ./mycli-full --configFile $HOME/.tatcli/config.local.json demo /YouTopic/subTopic your message\n\n File main.go\n\npackage main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\n\tlog \"github.com/Sirupsen/logrus\"\n\t\"github.com/ovh/tat\"\n\t\"github.com/spf13/cobra\"\n\t\"github.com/spf13/viper\"\n)\n\nvar rootCmd = &cobra.Command{\n\tUse: \"mycli-full\",\n\tLong: SDK Use Demo,\n}\n\n// URL of tat engine, tat username and tat password\nvar (\n\thome = os.Getenv(\"HOME\")\n\ttaturl string\n\tusername string\n\tpassword string\n\n\t// ConfigFile is $HOME/.tatcli/config.json per default\n\t// contains user, password and url of tat\n\tconfigFile string\n)\n\nfunc main() {\n\taddCommands()\n\n\trootCmd.PersistentFlags().StringVarP(&taturl, \"url\", \"\", \"\", \"URL Tat Engine, facultative if you have a \"+home+\"/.tatcli/config.json file\")\n\trootCmd.PersistentFlags().StringVarP(&username, \"username\", \"u\", \"\", \"username, facultative if you have a \"+home+\"/.tatcli/config.json file\")\n\trootCmd.PersistentFlags().StringVarP(&password, \"password\", \"p\", \"\", \"password, facultative if you have a \"+home+\"/.tatcli/config.json file\")\n\trootCmd.PersistentFlags().StringVarP(&configFile, \"configFile\", \"c\", home+\"/.tatcli/config.json\", \"configuration file, default is \"+home+\"/.tatcli/config.json\")\n\n\tviper.BindPFlag(\"url\", rootCmd.PersistentFlags().Lookup(\"url\"))\n\tviper.BindPFlag(\"username\", rootCmd.PersistentFlags().Lookup(\"username\"))\n\tviper.BindPFlag(\"password\", rootCmd.PersistentFlags().Lookup(\"password\"))\n\n\tlog.SetLevel(log.DebugLevel)\n\n\tif err := rootCmd.Execute(); err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(-1)\n\t}\n}\n\n//AddCommands adds child commands to the root command rootCmd.\nfunc addCommands() {\n\trootCmd.AddCommand(cmdDemo)\n}\n\nvar cmdDemo = &cobra.Command{\n\tUse: \"demo topic msg\",\n\tShort: \"Demo Post Msg\",\n\tRun: func(cmd *cobra.Command, args []string) {\n\t\tcreate(args[0], args[1])\n\t},\n}\n\n// create creates a message in specified topic\nfunc create(topic, message string) {\n\treadConfig()\n\tm := tat.MessageJSON{Text: message, Topic: topic}\n\tmsgCreated, err := getClient().MessageAdd(m)\n\tif err != nil {\n\t\tlog.Errorf(\"Error:%s\", err)\n\t\treturn\n\t}\n\tlog.Debugf(\"ID Message Created: %d\", msgCreated.Message.ID)\n}\n\nfunc getClient() *tat.Client {\n\ttc, err := tat.NewClient(tat.Options{\n\t\tURL: viper.GetString(\"url\"),\n\t\tUsername: viper.GetString(\"username\"),\n\t\tPassword: viper.GetString(\"password\"),\n\t\tReferer: \"mycli.v0\",\n\t})\n\n\tif err != nil {\n\t\tlog.Fatalf(\"Error while create new Tat Client: %s\", err)\n\t}\n\n\ttat.DebugLogFunc = log.Debugf\n\treturn tc\n}\n\n// readConfig reads config in .tatcli/config per default\nfunc readConfig() {\n\tif configFile != \"\" {\n\t\tviper.SetConfigFile(configFile)\n\t\tviper.ReadInConfig() // Find and read the config file\n\t}\n}\n\nNotice\nYou should split this file into many files.\n\nSee https://github.com/ovh/tat/tatcli for CLI with many subcommands.\n", "tags": [] }, { @@ -140,7 +140,7 @@ { "uri": "./tat/tatcli/general", "title": "General", - "content": "---\ntitle: \"General\"\nweight: 1\ntoc: true\nprev: \"/tatcli\"\nnext: \"/tatcli/tatcli-config\"\n\n---\n\nimg align=\"right\" src=\"https://raw.githubusercontent.com/ovh/tat/master/tat.png\"\n\nTatcli, a Tat Command Line Interface.\n\nSee Tat Engine for more information: https://github.com/ovh/tat\n\nDownload\nDownload latest binary on release page https://github.com/ovh/tatcli/releases\nthen chmod +x tatcli\n\nIf you have already installed tatcli, you can update it with tatcli update.\n\n Usage - General Rules\n\nA successful command will give you no feedback. If you want one, you can use -v argument.\nAfter each command, the exit code can be found in the $? variable. No error if exit code equals 0.\n", + "content": "---\ntitle: \"General\"\nweight: 1\ntoc: true\nprev: \"/tatcli\"\nnext: \"/tatcli/tatcli-config\"\n\n---\n\nimg align=\"right\" src=\"https://raw.githubusercontent.com/ovh/tat/master/tat.png\"\n\nTatcli, a Tat Command Line Interface.\n\nSee Tat Engine for more information: https://github.com/ovh/tat\n\nDownload\nDownload latest binary on release page https://github.com/ovh/tat/tatcli/releases\nthen chmod +x tatcli\n\nIf you have already installed tatcli, you can update it with tatcli update.\n\n Usage - General Rules\n\nA successful command will give you no feedback. If you want one, you can use -v argument.\nAfter each command, the exit code can be found in the $? variable. No error if exit code equals 0.\n", "tags": [] }, { diff --git a/docs/overview/architecture/index.html b/docs/overview/architecture/index.html index 28cb21b..04f229b 100644 --- a/docs/overview/architecture/index.html +++ b/docs/overview/architecture/index.html @@ -3,7 +3,7 @@ - + @@ -703,7 +703,7 @@

Architecture

more information. Source: http://github.com/ovh/tatwebui
  • Tatcli, the TAT Command Line Interface. All Tat features are available on tatcli. You can use it for “one shot” action on Tat Engine, or for display a UI in command line with tatcli ui. Tatcli ui -is popular to keep an eye on alerts or monitoring events without having a browser on it. Source: http://github.com/ovh/tatcli
  • +is popular to keep an eye on alerts or monitoring events without having a browser on it. Source: http://github.com/ovh/tat/tatcli
  • uServices: Tat Engine is simple to be used, it’s also easy to develop uService above tat to make things a little more advanced, like on-call schedule & intervention, reporting, etc… You’ll find some opensourced uService in chapter Ecosystem
  • diff --git a/docs/overview/concepts/index.html b/docs/overview/concepts/index.html index ff9848d..fff89f6 100644 --- a/docs/overview/concepts/index.html +++ b/docs/overview/concepts/index.html @@ -3,7 +3,7 @@ - + diff --git a/docs/overview/contribute/index.html b/docs/overview/contribute/index.html index 683c212..11017ae 100644 --- a/docs/overview/contribute/index.html +++ b/docs/overview/contribute/index.html @@ -3,7 +3,7 @@ - + @@ -727,7 +727,7 @@

    Main Components

    Views

    diff --git a/docs/overview/index.html b/docs/overview/index.html index af50e9a..0d68ff7 100644 --- a/docs/overview/index.html +++ b/docs/overview/index.html @@ -3,7 +3,7 @@ - + diff --git a/docs/overview/index.xml b/docs/overview/index.xml index 3b1379a..1e45fb2 100644 --- a/docs/overview/index.xml +++ b/docs/overview/index.xml @@ -1,9 +1,9 @@ - Overview-rsses on TAT - TextAndTag Documentation + Overviews on TAT - TextAndTag Documentation https://ovh.github.io/tat/overview/index.xml - Recent content in Overview-rsses on TAT - TextAndTag Documentation + Recent content in Overviews on TAT - TextAndTag Documentation Hugo -- gohugo.io en-us @@ -42,7 +42,7 @@ &hellip;</li> </ul> -<p>Tat Engine exposes only an HTTP REST API. You can manipulate this API with Tat Command Line Interface, aka tatcli, see <a href="https://github.com/ovh/tatcli">https://github.com/ovh/tatcli</a>.</p> +<p>Tat Engine exposes only an HTTP REST API. You can manipulate this API with Tat Command Line Interface, aka tatcli, see <a href="https://github.com/ovh/tat/tatcli">https://github.com/ovh/tat/tatcli</a>.</p> <p>A WebUI is also available, see <a href="https://github.com/ovh/tatwebui">https://github.com/ovh/tatwebui</a>.</p> @@ -251,7 +251,7 @@ is component oriented, your can display messages with different Views. See <a more information. Source: <a href="http://github.com/ovh/tatwebui">http://github.com/ovh/tatwebui</a></li> <li>Tatcli, the TAT Command Line Interface. All Tat features are available on tatcli. You can use it for &ldquo;one shot&rdquo; action on Tat Engine, or for display a UI in command line with <code>tatcli ui</code>. Tatcli ui -is popular to keep an eye on alerts or monitoring events without having a browser on it. Source: <a href="http://github.com/ovh/tatcli">http://github.com/ovh/tatcli</a></li> +is popular to keep an eye on alerts or monitoring events without having a browser on it. Source: <a href="http://github.com/ovh/tat/tatcli">http://github.com/ovh/tat/tatcli</a></li> <li>uServices: Tat Engine is simple to be used, it&rsquo;s also easy to develop uService above tat to make things a little more advanced, like on-call schedule &amp; intervention, reporting, etc&hellip; You&rsquo;ll find some opensourced uService in chapter <a href="https://ovh.github.io/tat/ecosystem">Ecosystem</a></li> @@ -279,7 +279,7 @@ to hear from you! Make sure to read CONTRIBUTING file on repository concerned be <ul> <li>Tat Engine <a href="https://ovh.github.io/tat/engine/">Doc</a> - <a href="http://github.com/ovh/tat">http://github.com/ovh/tat</a> - <a href="http://github.com/ovh/tat/blob/master/LICENSE">LICENSE</a> - <a href="http://github.com/ovh/tat/blob/master/CONTRIBUTING.md">CONTRIBUTING</a></li> <li>Tatwebui <a href="https://ovh.github.io/tat/tatwebui/">Doc</a> - <a href="http://github.com/ovh/tatwebui">http://github.com/ovh/tatwebui</a> - <a href="http://github.com/ovh/tatwebui/blob/master/LICENSE">LICENSE</a> - <a href="http://github.com/ovh/tatwebui/blob/master/CONTRIBUTING.md">CONTRIBUTING</a></li> -<li>Tatcli <a href="https://ovh.github.io/tat/tatcli/">Doc</a> - <a href="http://github.com/ovh/tatcli">http://github.com/ovh/tatcli</a> - <a href="http://github.com/ovh/tatcli/blob/master/LICENSE">LICENSE</a> - <a href="http://github.com/ovh/tatcli/blob/master/CONTRIBUTING.md">CONTRIBUTING</a></li> +<li>Tatcli <a href="https://ovh.github.io/tat/tatcli/">Doc</a> - <a href="http://github.com/ovh/tat/tatcli">http://github.com/ovh/tat/tatcli</a> - <a href="http://github.com/ovh/tat/tatcli/blob/master/LICENSE">LICENSE</a> - <a href="http://github.com/ovh/tat/tatcli/blob/master/CONTRIBUTING.md">CONTRIBUTING</a></li> </ul> <h3 id="views">Views</h3> diff --git a/docs/overview/introduction/index.html b/docs/overview/introduction/index.html index 5ceed87..70f66ef 100644 --- a/docs/overview/introduction/index.html +++ b/docs/overview/introduction/index.html @@ -3,7 +3,7 @@ - + @@ -703,7 +703,7 @@

    Introduction

    … -

    Tat Engine exposes only an HTTP REST API. You can manipulate this API with Tat Command Line Interface, aka tatcli, see https://github.com/ovh/tatcli.

    +

    Tat Engine exposes only an HTTP REST API. You can manipulate this API with Tat Command Line Interface, aka tatcli, see https://github.com/ovh/tat/tatcli.

    A WebUI is also available, see https://github.com/ovh/tatwebui.

    diff --git a/docs/overview/lifecycle/index.html b/docs/overview/lifecycle/index.html index 7d53a59..0ce188d 100644 --- a/docs/overview/lifecycle/index.html +++ b/docs/overview/lifecycle/index.html @@ -3,7 +3,7 @@ - + diff --git a/docs/sdk/full-example/index.html b/docs/sdk/full-example/index.html index be0a254..8aea1a3 100644 --- a/docs/sdk/full-example/index.html +++ b/docs/sdk/full-example/index.html @@ -732,7 +732,7 @@

    Notice

    You should split this file into many files.

    -

    See https://github.com/ovh/tatcli for CLI with many subcommands.

    +

    See https://github.com/ovh/tat/tatcli for CLI with many subcommands.

    diff --git a/docs/sdk/golang-full-example/index.html b/docs/sdk/golang-full-example/index.html index 7719c2f..c28d13d 100644 --- a/docs/sdk/golang-full-example/index.html +++ b/docs/sdk/golang-full-example/index.html @@ -3,7 +3,7 @@ - + @@ -829,7 +829,7 @@

    Notice

    You should split this file into many files.

    -

    See https://github.com/ovh/tatcli for CLI with many subcommands.

    +

    See https://github.com/ovh/tat/tatcli for CLI with many subcommands.

    diff --git a/docs/sdk/golang-simple-main/index.html b/docs/sdk/golang-simple-main/index.html index 9997731..97be5e4 100644 --- a/docs/sdk/golang-simple-main/index.html +++ b/docs/sdk/golang-simple-main/index.html @@ -3,7 +3,7 @@ - + diff --git a/docs/sdk/index.html b/docs/sdk/index.html index f40a388..9c69dc8 100644 --- a/docs/sdk/index.html +++ b/docs/sdk/index.html @@ -3,7 +3,7 @@ - + diff --git a/docs/sdk/index.xml b/docs/sdk/index.xml index a87312d..9cf58a5 100644 --- a/docs/sdk/index.xml +++ b/docs/sdk/index.xml @@ -1,9 +1,9 @@ - Sdk-rsses on TAT - TextAndTag Documentation + Sdks on TAT - TextAndTag Documentation https://ovh.github.io/tat/sdk/index.xml - Recent content in Sdk-rsses on TAT - TextAndTag Documentation + Recent content in Sdks on TAT - TextAndTag Documentation Hugo -- gohugo.io en-us @@ -232,7 +232,7 @@ func readConfig() { <p>You should split this file into many files.</p> -<p>See <a href="https://github.com/ovh/tatcli">https://github.com/ovh/tatcli</a> for CLI with many subcommands.</p> +<p>See <a href="https://github.com/ovh/tat/tatcli">https://github.com/ovh/tat/tatcli</a> for CLI with many subcommands.</p> diff --git a/docs/sitemap.xml b/docs/sitemap.xml index 52c87c1..e32fa0d 100644 --- a/docs/sitemap.xml +++ b/docs/sitemap.xml @@ -1,34 +1,6 @@ - - https://ovh.github.io/tat/ - - - - https://ovh.github.io/tat/ecosystem/ - - - - https://ovh.github.io/tat/overview/ - - - - https://ovh.github.io/tat/tatcli/ - - - - https://ovh.github.io/tat/engine/ - - - - https://ovh.github.io/tat/sdk/ - - - - https://ovh.github.io/tat/tatwebui/ - - https://ovh.github.io/tat/engine/general/ @@ -209,4 +181,68 @@ https://ovh.github.io/tat/engine/production-installation/ + + https://ovh.github.io/tat/ecosystem/ + + + + https://ovh.github.io/tat/ecosystem/ + 0 + + + + https://ovh.github.io/tat/engine/ + 0 + + + + https://ovh.github.io/tat/overview/ + + + + https://ovh.github.io/tat/overview/ + 0 + + + + https://ovh.github.io/tat/sdk/ + 0 + + + + https://ovh.github.io/tat/ + 0 + + + + https://ovh.github.io/tat/tatcli/ + + + + https://ovh.github.io/tat/engine/ + + + + https://ovh.github.io/tat/sdk/ + + + + https://ovh.github.io/tat/tatwebui/ + + + + https://ovh.github.io/tat/tatcli/ + 0 + + + + https://ovh.github.io/tat/tatnhack/ + 0 + + + + https://ovh.github.io/tat/tatwebui/ + 0 + + \ No newline at end of file diff --git a/docs/tatcli/general/index.html b/docs/tatcli/general/index.html index e265fdc..cbfba73 100644 --- a/docs/tatcli/general/index.html +++ b/docs/tatcli/general/index.html @@ -3,7 +3,7 @@ - + @@ -718,7 +718,7 @@

    General

    Download

    -

    Download latest binary on release page https://github.com/ovh/tatcli/releases +

    Download latest binary on release page https://github.com/ovh/tat/tatcli/releases then chmod +x tatcli

    If you have already installed tatcli, you can update it with tatcli update.

    diff --git a/docs/tatcli/index.html b/docs/tatcli/index.html index 2fc4397..869a9cc 100644 --- a/docs/tatcli/index.html +++ b/docs/tatcli/index.html @@ -3,7 +3,7 @@ - + diff --git a/docs/tatcli/index.xml b/docs/tatcli/index.xml index 9ccdea2..8b31a9e 100644 --- a/docs/tatcli/index.xml +++ b/docs/tatcli/index.xml @@ -1,9 +1,9 @@ - Tatcli-rsses on TAT - TextAndTag Documentation + Tatclis on TAT - TextAndTag Documentation https://ovh.github.io/tat/tatcli/index.xml - Recent content in Tatcli-rsses on TAT - TextAndTag Documentation + Recent content in Tatclis on TAT - TextAndTag Documentation Hugo -- gohugo.io en-us @@ -40,7 +40,7 @@ <h2 id="download">Download</h2> -<p>Download latest binary on release page <a href="https://github.com/ovh/tatcli/releases">https://github.com/ovh/tatcli/releases</a> +<p>Download latest binary on release page <a href="https://github.com/ovh/tat/tatcli/releases">https://github.com/ovh/tat/tatcli/releases</a> then <code>chmod +x tatcli</code></p> <p>If you have already installed tatcli, you can update it with <code>tatcli update</code>.</p> @@ -524,7 +524,7 @@ Available Commands: deleteRwGroup Delete Read Write Groups from a topic: tatcli topic deleteRwGroup [--recursive] &lt;topic&gt; &lt;groupname1&gt; [&lt;groupname2&gt;]... deleteRwUser Delete Read Write Users from a topic: tatcli topic deleteRwUser [--recursive] &lt;topic&gt; &lt;username1&gt; [username2]... list List all topics: tatcli topic list [&lt;skip&gt;] [&lt;limit&gt;], tatcli topic list -h for see all criterias - parameter Update param on one topic: tatcli topic param [--recursive] &lt;topic&gt; &lt;maxLength&gt; &lt;canForceDate&gt; &lt;canUpdateMsg&gt; &lt;canDeleteMsg&gt; &lt;canUpdateAllMsg&gt; &lt;canDeleteAllMsg&gt; &lt;adminCanUpdateAllMsg&gt; &lt;adminCanDeleteAllMsg&gt; &lt;isAutoComputeTags&gt; &lt;isAutoComputeLabels&gt; + parameter Update param on one topic: tatcli topic param [--recursive] &lt;topic&gt; &lt;maxReplies&gt; &lt;maxLength&gt; &lt;canForceDate&gt; &lt;canUpdateMsg&gt; &lt;canDeleteMsg&gt; &lt;canUpdateAllMsg&gt; &lt;canDeleteAllMsg&gt; &lt;adminCanUpdateAllMsg&gt; &lt;adminCanDeleteAllMsg&gt; &lt;isAutoComputeTags&gt; &lt;isAutoComputeLabels&gt; truncate Remove all messages in a topic, only for tat admin and administrators on topic : tatcli topic truncate &lt;topic&gt; [--force] truncatelabels Truncate Labels on this topic, only for tat admin and administrators on topic : tatcli topic truncatelabels &lt;topic&gt; truncatetags Truncate Tags on this topic, only for tat admin and administrators on topic : tatcli topic truncatetags &lt;topic&gt; diff --git a/docs/tatcli/tatcli-config/index.html b/docs/tatcli/tatcli-config/index.html index debcd80..63fd16f 100644 --- a/docs/tatcli/tatcli-config/index.html +++ b/docs/tatcli/tatcli-config/index.html @@ -3,7 +3,7 @@ - + diff --git a/docs/tatcli/tatcli-group/index.html b/docs/tatcli/tatcli-group/index.html index 65a4e34..f46b185 100644 --- a/docs/tatcli/tatcli-group/index.html +++ b/docs/tatcli/tatcli-group/index.html @@ -3,7 +3,7 @@ - + diff --git a/docs/tatcli/tatcli-message/index.html b/docs/tatcli/tatcli-message/index.html index 4885f0b..11226a9 100644 --- a/docs/tatcli/tatcli-message/index.html +++ b/docs/tatcli/tatcli-message/index.html @@ -3,7 +3,7 @@ - + diff --git a/docs/tatcli/tatcli-presence/index.html b/docs/tatcli/tatcli-presence/index.html index 6beb554..cb0a347 100644 --- a/docs/tatcli/tatcli-presence/index.html +++ b/docs/tatcli/tatcli-presence/index.html @@ -3,7 +3,7 @@ - + diff --git a/docs/tatcli/tatcli-stats/index.html b/docs/tatcli/tatcli-stats/index.html index d1dafa8..b84eb19 100644 --- a/docs/tatcli/tatcli-stats/index.html +++ b/docs/tatcli/tatcli-stats/index.html @@ -3,7 +3,7 @@ - + diff --git a/docs/tatcli/tatcli-system/index.html b/docs/tatcli/tatcli-system/index.html index eae24d9..2d72d05 100644 --- a/docs/tatcli/tatcli-system/index.html +++ b/docs/tatcli/tatcli-system/index.html @@ -3,7 +3,7 @@ - + diff --git a/docs/tatcli/tatcli-topic/index.html b/docs/tatcli/tatcli-topic/index.html index 5dbefa8..1577f74 100644 --- a/docs/tatcli/tatcli-topic/index.html +++ b/docs/tatcli/tatcli-topic/index.html @@ -3,7 +3,7 @@ - + @@ -768,7 +768,7 @@

    tatcli topic -h

    deleteRwGroup Delete Read Write Groups from a topic: tatcli topic deleteRwGroup [--recursive] <topic> <groupname1> [<groupname2>]... deleteRwUser Delete Read Write Users from a topic: tatcli topic deleteRwUser [--recursive] <topic> <username1> [username2]... list List all topics: tatcli topic list [<skip>] [<limit>], tatcli topic list -h for see all criterias - parameter Update param on one topic: tatcli topic param [--recursive] <topic> <maxLength> <canForceDate> <canUpdateMsg> <canDeleteMsg> <canUpdateAllMsg> <canDeleteAllMsg> <adminCanUpdateAllMsg> <adminCanDeleteAllMsg> <isAutoComputeTags> <isAutoComputeLabels> + parameter Update param on one topic: tatcli topic param [--recursive] <topic> <maxReplies> <maxLength> <canForceDate> <canUpdateMsg> <canDeleteMsg> <canUpdateAllMsg> <canDeleteAllMsg> <adminCanUpdateAllMsg> <adminCanDeleteAllMsg> <isAutoComputeTags> <isAutoComputeLabels> truncate Remove all messages in a topic, only for tat admin and administrators on topic : tatcli topic truncate <topic> [--force] truncatelabels Truncate Labels on this topic, only for tat admin and administrators on topic : tatcli topic truncatelabels <topic> truncatetags Truncate Tags on this topic, only for tat admin and administrators on topic : tatcli topic truncatetags <topic> diff --git a/docs/tatcli/tatcli-ui/index.html b/docs/tatcli/tatcli-ui/index.html index 5405783..3f50f11 100644 --- a/docs/tatcli/tatcli-ui/index.html +++ b/docs/tatcli/tatcli-ui/index.html @@ -3,7 +3,7 @@ - + diff --git a/docs/tatcli/tatcli-update/index.html b/docs/tatcli/tatcli-update/index.html index 0557747..11a587f 100644 --- a/docs/tatcli/tatcli-update/index.html +++ b/docs/tatcli/tatcli-update/index.html @@ -3,7 +3,7 @@ - + diff --git a/docs/tatcli/tatcli-user/index.html b/docs/tatcli/tatcli-user/index.html index 401460d..b9463c4 100644 --- a/docs/tatcli/tatcli-user/index.html +++ b/docs/tatcli/tatcli-user/index.html @@ -3,7 +3,7 @@ - + diff --git a/docs/tatcli/tatcli-version/index.html b/docs/tatcli/tatcli-version/index.html index a370a65..c3306ba 100644 --- a/docs/tatcli/tatcli-version/index.html +++ b/docs/tatcli/tatcli-version/index.html @@ -3,7 +3,7 @@ - + diff --git a/docs/tatnhack/index.html b/docs/tatnhack/index.html index 51b98e1..9eb08a1 100644 --- a/docs/tatnhack/index.html +++ b/docs/tatnhack/index.html @@ -3,7 +3,7 @@ - + diff --git a/docs/tatnhack/index.xml b/docs/tatnhack/index.xml index c435542..56b5d97 100644 --- a/docs/tatnhack/index.xml +++ b/docs/tatnhack/index.xml @@ -1,9 +1,9 @@ - Tatnhack-rsses on TAT - TextAndTag Documentation + Tatnhacks on TAT - TextAndTag Documentation https://ovh.github.io/tat/tatnhack/index.xml - Recent content in Tatnhack-rsses on TAT - TextAndTag Documentation + Recent content in Tatnhacks on TAT - TextAndTag Documentation Hugo -- gohugo.io en-us diff --git a/docs/tatnhack/monitoring-process/index.html b/docs/tatnhack/monitoring-process/index.html index 5c67e62..71e0b32 100644 --- a/docs/tatnhack/monitoring-process/index.html +++ b/docs/tatnhack/monitoring-process/index.html @@ -3,7 +3,7 @@ - + diff --git a/docs/tatnhack/visual-feedback/index.html b/docs/tatnhack/visual-feedback/index.html index 5ccf655..55186ff 100644 --- a/docs/tatnhack/visual-feedback/index.html +++ b/docs/tatnhack/visual-feedback/index.html @@ -3,7 +3,7 @@ - + diff --git a/docs/tatwebui/cdsview/index.html b/docs/tatwebui/cdsview/index.html index 8074907..e844779 100644 --- a/docs/tatwebui/cdsview/index.html +++ b/docs/tatwebui/cdsview/index.html @@ -3,7 +3,7 @@ - + diff --git a/docs/tatwebui/dashingview/index.html b/docs/tatwebui/dashingview/index.html index 8c835b9..6b359f4 100644 --- a/docs/tatwebui/dashingview/index.html +++ b/docs/tatwebui/dashingview/index.html @@ -3,7 +3,7 @@ - + diff --git a/docs/tatwebui/development/index.html b/docs/tatwebui/development/index.html index e372cf1..40d7347 100644 --- a/docs/tatwebui/development/index.html +++ b/docs/tatwebui/development/index.html @@ -3,7 +3,7 @@ - + diff --git a/docs/tatwebui/index.html b/docs/tatwebui/index.html index b791b10..15b27a3 100644 --- a/docs/tatwebui/index.html +++ b/docs/tatwebui/index.html @@ -3,7 +3,7 @@ - + diff --git a/docs/tatwebui/index.xml b/docs/tatwebui/index.xml index d00b83e..5f6fbe0 100644 --- a/docs/tatwebui/index.xml +++ b/docs/tatwebui/index.xml @@ -1,9 +1,9 @@ - Tatwebui-rsses on TAT - TextAndTag Documentation + Tatwebuis on TAT - TextAndTag Documentation https://ovh.github.io/tat/tatwebui/index.xml - Recent content in Tatwebui-rsses on TAT - TextAndTag Documentation + Recent content in Tatwebuis on TAT - TextAndTag Documentation Hugo -- gohugo.io en-us diff --git a/docs/tatwebui/introduction/index.html b/docs/tatwebui/introduction/index.html index 80e9c52..a7464be 100644 --- a/docs/tatwebui/introduction/index.html +++ b/docs/tatwebui/introduction/index.html @@ -3,7 +3,7 @@ - + diff --git a/docs/tatwebui/monitoringview/index.html b/docs/tatwebui/monitoringview/index.html index 9c61694..52820ca 100644 --- a/docs/tatwebui/monitoringview/index.html +++ b/docs/tatwebui/monitoringview/index.html @@ -3,7 +3,7 @@ - + diff --git a/docs/tatwebui/notificationsview/index.html b/docs/tatwebui/notificationsview/index.html index d410636..cd79ca8 100644 --- a/docs/tatwebui/notificationsview/index.html +++ b/docs/tatwebui/notificationsview/index.html @@ -3,7 +3,7 @@ - + diff --git a/docs/tatwebui/pastatview/index.html b/docs/tatwebui/pastatview/index.html index e1bc595..c16cfd0 100644 --- a/docs/tatwebui/pastatview/index.html +++ b/docs/tatwebui/pastatview/index.html @@ -3,7 +3,7 @@ - + diff --git a/docs/tatwebui/releaseview/index.html b/docs/tatwebui/releaseview/index.html index f7b052a..1730677 100644 --- a/docs/tatwebui/releaseview/index.html +++ b/docs/tatwebui/releaseview/index.html @@ -3,7 +3,7 @@ - + diff --git a/docs/tatwebui/standardview/index.html b/docs/tatwebui/standardview/index.html index 1ec1fee..586fba3 100644 --- a/docs/tatwebui/standardview/index.html +++ b/docs/tatwebui/standardview/index.html @@ -3,7 +3,7 @@ - + diff --git a/package.sh b/package.sh index 43ab22e..510ff94 100755 --- a/package.sh +++ b/package.sh @@ -1,5 +1,6 @@ #!/bin/bash +# tat cd api for GOOS in darwin linux ; do GOARCH=amd64 @@ -12,3 +13,18 @@ for GOOS in darwin linux ; do file bin/tat-${architecture} echo "ldd bin/tat-${architecture}" done + +# tatcli +cd ../tatcli +for GOOS in windows darwin linux freebsd; do + for GOARCH in 386 amd64 arm; do + if [[ $GOARCH == "arm" && $GOOS != "linux" ]]; then + continue; + fi; + architecture="${GOOS}-${GOARCH}" + echo "Building ${architecture} ${path}" + export GOOS=$GOOS + export GOARCH=$GOARCH + go build -ldflags "-X github.com/ovh/tat/tatcli/update.architecture=${architecture}" -o bin/tatcli-${architecture} + done +done diff --git a/tatcli/.gitignore b/tatcli/.gitignore new file mode 100644 index 0000000..9b88ed4 --- /dev/null +++ b/tatcli/.gitignore @@ -0,0 +1,3 @@ +tatcli +.DS_Store +bin/ diff --git a/tatcli/.travis.yml b/tatcli/.travis.yml new file mode 100644 index 0000000..306f645 --- /dev/null +++ b/tatcli/.travis.yml @@ -0,0 +1,32 @@ +language: go +go: +- 1.6 +env: + global: + - URL_UPDATE_SNAPSHOT="" + - PROJECT_NAME="tatcli" + - PROJECT_PATH="github.com/ovh" + +install: true + +script: chmod +x package.sh && ./package.sh + +before_deploy: + - gem install mime-types -v 2.6.2 + +deploy: + provider: releases + api_key: + secure: o7I8QKlnHLi0Wl9mBbz24CiMkFMLShAculD1w6Y5XBLQ/+PlHfZ8r9DGvi/3El0pJvqJY1OOvN1yh5d1cCDnhZYpZoMIsEKHhUss/CSNsHBalPiOyvaADDPpPGyLZwsNTvtmTXHZcJZ2Z1IC45lMANMCLzERjAAkacfv79GCIWMURWqd76Fa7uY8wX5k6kYLQeu2CL3TsVE6oM2YZvC9GE96qS2H0Z3Qo4nuuto2XJ6ihutOGkYwF0lnywuuxRz6PkyIFVqMhXJVJLJ0ygZKYRQ9AmH6WUe8KBAizmwH8ZN+6C1xakUut6ynhFlcAINtKahQ/Qr6ZPIbOK3rytCZKeyUaRVZ72p01nZMOOU2dRktkEiRLFaSZ9AQXqoQMMQmZLi6t1cptRMQw8znoZ6c/g63FsE6RchXqTr/QjNHKunoW8LYb4FYsXZ8yJAtrC3btJP1t/dG7iKs98oCUPGegu5fX0pd7wU5BBjg0CJOVhIpZB1qkPlkiQ004IzvQPKhJN1a8qGAULobRFMYwcJRLwDHOmaX2UmeF/r3R8cdBB1LZm4/YTI+T1tPs+RZK5wHqgsk47nhodSvfUcApJ525MlBWbypmwcvTEY4rjZ9mr1aIgpLzzfsrP2G2nbiPjuvwd2bE0Fhaitq0UPYB/8xIWOv9GpfW+fMvkMfCqYgQJg= + file: + - bin/tatcli-darwin-386 + - bin/tatcli-darwin-amd64 + - bin/tatcli-freebsd-386 + - bin/tatcli-freebsd-amd64 + - bin/tatcli-linux-386 + - bin/tatcli-linux-amd64 + - bin/tatcli-linux-arm + - bin/tatcli-windows-386 + - bin/tatcli-windows-amd64 + on: + tags: true diff --git a/tatcli/CONTRIBUTING.md b/tatcli/CONTRIBUTING.md new file mode 100644 index 0000000..d6d85b5 --- /dev/null +++ b/tatcli/CONTRIBUTING.md @@ -0,0 +1,82 @@ +# Contributing to Tatcli + +This project accepts contributions. In order to contribute, you should +pay attention to a few things: + +1. your code must follow the coding style rules +2. your code must be fully documented +3. your work must be signed +4. GitHub Pull Requests + +## Coding and documentation Style: + +- Code must be formated with `go fmt` +- Code must pass `go vet` +- Code must pass `golint` + +## Submitting Modifications: + +The contributions should be github Pull Requests. The guidelines are the same +as the patch submission for the Linux kernel except for the DCO which +is defined below. The guidelines are defined in the +'SubmittingPatches' file, available in the directory 'Documentation' +of the Linux kernel source tree. + +It can be accessed online too: + +https://www.kernel.org/doc/Documentation/SubmittingPatches + +You can submit your patches via GitHub + +## Licensing for new files: + +Tatcli is licensed under a (modified) BSD license. Anything contributed to +Tatcli must be released under this license. + +When introducing a new file into the project, please make sure it has a +copyright header making clear under which license it''s being released. + +## Developer Certificate of Origin: + +``` +To improve tracking of contributions to this project we will use a +process modeled on the modified DCO 1.1 and use a "sign-off" procedure +on patches that are being contributed. + +The sign-off is a simple line at the end of the explanation for the +patch, which certifies that you wrote it or otherwise have the right +to pass it on as an open-source patch. The rules are pretty simple: +if you can certify the below: + +By making a contribution to this project, I certify that: + +(a) The contribution was created in whole or in part by me and I have + the right to submit it under the open source license indicated in + the file; or + +(b) The contribution is based upon previous work that, to the best of + my knowledge, is covered under an appropriate open source License + and I have the right under that license to submit that work with + modifications, whether created in whole or in part by me, under + the same open source license (unless I am permitted to submit + under a different license), as indicated in the file; or + +(c) The contribution was provided directly to me by some other person + who certified (a), (b) or (c) and I have not modified it. + +(d) The contribution is made free of any other party''s intellectual + property claims or rights. + +(e) I understand and agree that this project and the contribution are + public and that a record of the contribution (including all + personal information I submit with it, including my sign-off) is + maintained indefinitely and may be redistributed consistent with + this project or the open source license(s) involved. + + +then you just add a line saying + + Signed-off-by: Random J Developer + +using your real name (sorry, no pseudonyms or anonymous contributions.) +``` diff --git a/tatcli/LICENSE b/tatcli/LICENSE new file mode 100644 index 0000000..045526c --- /dev/null +++ b/tatcli/LICENSE @@ -0,0 +1,25 @@ +Copyright (c) 2015-2016, OVH SAS. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of OVH SAS nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY OVH SAS AND CONTRIBUTORS ``AS IS'' AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL OVH SAS AND CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/tatcli/README.md b/tatcli/README.md new file mode 100644 index 0000000..10b8bf6 --- /dev/null +++ b/tatcli/README.md @@ -0,0 +1,18 @@ +[![Build Status](https://travis-ci.org/ovh/tatcli.svg?branch=master)](https://travis-ci.org/ovh/tatcli) +[![GoDoc](https://godoc.org/github.com/ovh/tat/tatcli?status.svg)](https://godoc.org/github.com/ovh/tat/tatcli) +[![Go Report Card](https://goreportcard.com/badge/ovh/tatcli)](https://goreportcard.com/report/ovh/tatcli) + +# Tat Command Line Interface + + + +Documentation: https://ovh.github.io/tat/tatcli/ + +# Hacking + +You've developed a new cool feature? Fixed an annoying bug? We'd be happy +to hear from you! Make sure to read [CONTRIBUTING.md](./CONTRIBUTING.md) before. + +# License + +This work is under the BSD license, see the [LICENSE](LICENSE) file for details. diff --git a/tatcli/config/config.go b/tatcli/config/config.go new file mode 100644 index 0000000..9b19b4c --- /dev/null +++ b/tatcli/config/config.go @@ -0,0 +1,18 @@ +package config + +import "github.com/spf13/cobra" + +func init() { + Cmd.AddCommand(cmdConfigTemplate) + Cmd.AddCommand(cmdConfigShow) +} + +// Cmd config +var Cmd = &cobra.Command{ + Use: "config", + Short: "Config commands: tatcli config --help", + Long: `Config commands: tatcli config +The configuration file is also used by "tatcli ui" + `, + Aliases: []string{"c"}, +} diff --git a/tatcli/config/show.go b/tatcli/config/show.go new file mode 100644 index 0000000..93307dc --- /dev/null +++ b/tatcli/config/show.go @@ -0,0 +1,24 @@ +package config + +import ( + "fmt" + + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" + "github.com/spf13/viper" +) + +var cmdConfigShow = &cobra.Command{ + Use: "show", + Short: "Show Configuration: tatcli config show", + Run: func(cmd *cobra.Command, args []string) { + show() + }, +} + +func show() { + internal.ReadConfig() + fmt.Printf("username:%s\n", viper.GetString("username")) + fmt.Printf("password:%s\n", viper.GetString("password")) + fmt.Printf("url:%s\n", viper.GetString("url")) +} diff --git a/tatcli/config/write.go b/tatcli/config/write.go new file mode 100644 index 0000000..abfb171 --- /dev/null +++ b/tatcli/config/write.go @@ -0,0 +1,70 @@ +package config + +import ( + "encoding/json" + "fmt" + "io/ioutil" + "os" + "path" + + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" + "github.com/spf13/viper" +) + +var cmdConfigTemplate = &cobra.Command{ + Use: "template", + Short: "Write a template configuration file in $HOME/.tatcli/config.json: tatcli config template", + Run: func(cmd *cobra.Command, args []string) { + writeTemplate() + }, +} + +// TemplateJSONType describes .tatcli/config.json file +type TemplateJSONType struct { + Username string `json:"username"` + Password string `json:"password"` + URL string `json:"url"` + TatwebuiURL string `json:"tatwebui-url"` + PostHookRunAction string `json:"post-hook-run-action,omitempty"` + Filters []string `json:"filters,omitempty"` + Commands []string `json:"commands,omitempty"` + Hooks []Hook `json:"hooks"` +} + +type Hook struct { + Shortcut string `json:"shortcut"` + Command string `json:"command"` + Exec string `json:"exec"` + Topics []string `json:"topics"` +} + +func writeTemplate() { + var templateJSON TemplateJSONType + + if viper.GetString("username") != "" { + templateJSON.Username = viper.GetString("username") + } + if viper.GetString("password") != "" { + templateJSON.Password = viper.GetString("password") + } + if viper.GetString("url") != "" { + templateJSON.URL = viper.GetString("url") + } + if viper.GetString("tatwebui-url") != "" { + templateJSON.TatwebuiURL = viper.GetString("tatwebui-url") + } + + jsonStr, err := json.MarshalIndent(templateJSON, "", " ") + internal.Check(err) + jsonStr = append(jsonStr, '\n') + filename := internal.ConfigFile + + dir := path.Dir(filename) + if _, err := os.Stat(dir); os.IsNotExist(err) { + internal.Check(os.Mkdir(dir, 0740)) + } + + internal.Check(ioutil.WriteFile(filename, jsonStr, 0600)) + fmt.Printf("%s is written\n", filename) +} diff --git a/tatcli/group/add_admin_user.go b/tatcli/group/add_admin_user.go new file mode 100644 index 0000000..97665e0 --- /dev/null +++ b/tatcli/group/add_admin_user.go @@ -0,0 +1,19 @@ +package group + +import ( + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" +) + +var cmdGroupAddAdminUser = &cobra.Command{ + Use: "addAdminUser", + Short: "Add Admin Users to a group: tacli group addAdminUser [ ... ]", + Run: func(cmd *cobra.Command, args []string) { + if len(args) >= 2 { + err := internal.Client().GroupAddAdminUsers(args[0], args[1:]) + internal.Check(err) + } else { + internal.Exit("Invalid argument: tatcli group addAdminUser --help\n") + } + }, +} diff --git a/tatcli/group/add_user.go b/tatcli/group/add_user.go new file mode 100644 index 0000000..17c8016 --- /dev/null +++ b/tatcli/group/add_user.go @@ -0,0 +1,19 @@ +package group + +import ( + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" +) + +var cmdGroupAddUser = &cobra.Command{ + Use: "addUser", + Short: "Add Users to a group: tacli group addUser [ ... ]", + Run: func(cmd *cobra.Command, args []string) { + if len(args) >= 2 { + err := internal.Client().GroupAddUsers(args[0], args[1:]) + internal.Check(err) + } else { + internal.Exit("Invalid argument: tatcli group addUser --help\n") + } + }, +} diff --git a/tatcli/group/create.go b/tatcli/group/create.go new file mode 100644 index 0000000..3835584 --- /dev/null +++ b/tatcli/group/create.go @@ -0,0 +1,24 @@ +package group + +import ( + "strings" + + "github.com/ovh/tat" + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" +) + +var cmdGroupCreate = &cobra.Command{ + Use: "create", + Short: "create a new group: tatcli group create ", + Run: func(cmd *cobra.Command, args []string) { + if len(args) >= 2 { + description := strings.Join(args[1:], " ") + g, err := internal.Client().GroupCreate(tat.GroupJSON{Name: args[0], Description: description}) + internal.Check(err) + internal.Print(g) + } else { + internal.Exit("Invalid argument: tatcli group create --help\n") + } + }, +} diff --git a/tatcli/group/delete.go b/tatcli/group/delete.go new file mode 100644 index 0000000..c3da083 --- /dev/null +++ b/tatcli/group/delete.go @@ -0,0 +1,18 @@ +package group + +import ( + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" +) + +var cmdGroupDelete = &cobra.Command{ + Use: "delete", + Short: "delete a group: tatcli group delete ", + Run: func(cmd *cobra.Command, args []string) { + if len(args) == 1 { + internal.Client().GroupDelete(args[0]) + } else { + internal.Exit("Invalid argument: tatcli group delete --help\n") + } + }, +} diff --git a/tatcli/group/delete_admin_user.go b/tatcli/group/delete_admin_user.go new file mode 100644 index 0000000..bd87f25 --- /dev/null +++ b/tatcli/group/delete_admin_user.go @@ -0,0 +1,19 @@ +package group + +import ( + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" +) + +var cmdGroupDeleteAdminUser = &cobra.Command{ + Use: "deleteAdminUser", + Short: "Delete Admin Users from a group: tacli group deleteAdminUser [ ... ]", + Run: func(cmd *cobra.Command, args []string) { + if len(args) >= 2 { + err := internal.Client().GroupDeleteAdminUsers(args[0], args[1:]) + internal.Check(err) + } else { + internal.Exit("Invalid argument: tatcli group deleteAdminUser --help\n") + } + }, +} diff --git a/tatcli/group/delete_user.go b/tatcli/group/delete_user.go new file mode 100644 index 0000000..26879f9 --- /dev/null +++ b/tatcli/group/delete_user.go @@ -0,0 +1,19 @@ +package group + +import ( + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" +) + +var cmdGroupDeleteUser = &cobra.Command{ + Use: "deleteUser", + Short: "Delete Users from a group: tacli group deleteUser [ ... ]", + Run: func(cmd *cobra.Command, args []string) { + if len(args) >= 2 { + err := internal.Client().GroupDeleteUsers(args[0], args[1:]) + internal.Check(err) + } else { + internal.Exit("Invalid argument: tatcli group deleteUser --help\n") + } + }, +} diff --git a/tatcli/group/group.go b/tatcli/group/group.go new file mode 100644 index 0000000..042e48f --- /dev/null +++ b/tatcli/group/group.go @@ -0,0 +1,22 @@ +package group + +import "github.com/spf13/cobra" + +func init() { + Cmd.AddCommand(cmdGroupList) + Cmd.AddCommand(cmdGroupCreate) + Cmd.AddCommand(cmdGroupUpdate) + Cmd.AddCommand(cmdGroupDelete) + Cmd.AddCommand(cmdGroupAddUser) + Cmd.AddCommand(cmdGroupDeleteUser) + Cmd.AddCommand(cmdGroupAddAdminUser) + Cmd.AddCommand(cmdGroupDeleteAdminUser) +} + +// Cmd group +var Cmd = &cobra.Command{ + Use: "group", + Short: "Group commands: tatcli group --help", + Long: `Group commands: tatcli group `, + Aliases: []string{"g", "groups"}, +} diff --git a/tatcli/group/list.go b/tatcli/group/list.go new file mode 100644 index 0000000..2f01f76 --- /dev/null +++ b/tatcli/group/list.go @@ -0,0 +1,17 @@ +package group + +import ( + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" +) + +var cmdGroupList = &cobra.Command{ + Use: "list", + Short: "List all groups: tatcli group list ", + Run: func(cmd *cobra.Command, args []string) { + skip, limit := internal.GetSkipLimit(args) + out, err := internal.Client().GroupList(skip, limit) + internal.Check(err) + internal.Print(out) + }, +} diff --git a/tatcli/group/update.go b/tatcli/group/update.go new file mode 100644 index 0000000..c5a8418 --- /dev/null +++ b/tatcli/group/update.go @@ -0,0 +1,22 @@ +package group + +import ( + "strings" + + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" +) + +var cmdGroupUpdate = &cobra.Command{ + Use: "update", + Short: "update a group: tatcli group update ", + Run: func(cmd *cobra.Command, args []string) { + if len(args) >= 3 { + description := strings.Join(args[2:], " ") + err := internal.Client().GroupUpdate(args[0], args[1], description) + internal.Check(err) + } else { + internal.Exit("Invalid argument: tatcli group update --help\n") + } + }, +} diff --git a/tatcli/internal/config.go b/tatcli/internal/config.go new file mode 100644 index 0000000..9972ff6 --- /dev/null +++ b/tatcli/internal/config.go @@ -0,0 +1,51 @@ +package internal + +import ( + "fmt" + + "github.com/spf13/viper" +) + +var ( + // Verbose display return from Tat Engine + Verbose bool + + // Debug display Request and response from Tat Engine + Debug bool + + // ConfigFile is $HOME/.tatcli/config.json per default + // contains user, password and url of tat + ConfigFile string + + // SSLInsecureSkipVerify Skip certificate check with SSL connection + SSLInsecureSkipVerify bool + + // Pretty prints json return in pretty format + Pretty bool + + // ShowStackTrace prints stacktrace on tatcli panic + ShowStackTrace bool + + // URL of tat engine + URL string + + // TatwebuiURL of tat Web UI, used only by tatcli ui and facultative + TatwebuiURL string + + // Username of tat user + Username string + + // Password of tat user + Password string +) + +// ReadConfig reads config in .tatcli/config per default +func ReadConfig() { + if ConfigFile != "" { + viper.SetConfigFile(ConfigFile) + viper.ReadInConfig() // Find and read the config file + if Debug { + fmt.Printf("Using config file %s\n", ConfigFile) + } + } +} diff --git a/tatcli/internal/engine.go b/tatcli/internal/engine.go new file mode 100644 index 0000000..545dd48 --- /dev/null +++ b/tatcli/internal/engine.go @@ -0,0 +1,92 @@ +package internal + +import ( + "bytes" + "encoding/json" + "fmt" + "strconv" + + log "github.com/Sirupsen/logrus" + "github.com/ovh/tat" + "github.com/spf13/viper" +) + +var instance *tat.Client + +// Client return a new Tat Client +func Client() *tat.Client { + ReadConfig() + if instance != nil { + return instance + } + + tc, err := tat.NewClient(tat.Options{ + URL: viper.GetString("url"), + Username: viper.GetString("username"), + Password: viper.GetString("password"), + Referer: "tatcli.v." + tat.Version, + }) + + if err != nil { + log.Fatalf("Error while create new Tat Client: %s", err) + } + + tat.DebugLogFunc = log.Debugf + + if Debug { + tat.IsDebug = true + } + + return tc +} + +// GetSkipLimit gets skip and limit in args array +// default skip to 0 and limit to 10 +func GetSkipLimit(args []string) (int, int) { + skip := "0" + limit := "10" + if len(args) == 3 { + skip = args[1] + limit = args[2] + } else if len(args) == 2 { + skip = args[0] + limit = args[1] + } + s, e1 := strconv.Atoi(skip) + Check(e1) + l, e2 := strconv.Atoi(limit) + Check(e2) + return s, l +} + +func getJSON(s []byte) string { + if Pretty { + var out bytes.Buffer + json.Indent(&out, s, "", " ") + return out.String() + } + return string(s) +} + +// Print prints json return +func Print(v interface{}) { + switch v.(type) { + case []byte: + fmt.Printf("%s", v) + default: + out, err := tat.Sprint(v) + Check(err) + fmt.Print(getJSON(out)) + } +} + +// Check checks error, if != nil, throw panic +func Check(e error) { + if e != nil { + if ShowStackTrace { + panic(e) + } else { + log.Fatalf("%s", e) + } + } +} diff --git a/tatcli/internal/utils.go b/tatcli/internal/utils.go new file mode 100644 index 0000000..e2e0440 --- /dev/null +++ b/tatcli/internal/utils.go @@ -0,0 +1,12 @@ +package internal + +import ( + "fmt" + "os" +) + +// Exit func display an error message on stderr and exit 1 +func Exit(format string, args ...interface{}) { + fmt.Fprintf(os.Stderr, format, args...) + os.Exit(1) +} diff --git a/tatcli/main.go b/tatcli/main.go new file mode 100644 index 0000000..f4c9a45 --- /dev/null +++ b/tatcli/main.go @@ -0,0 +1,68 @@ +package main + +import ( + "fmt" + "os" + + "github.com/ovh/tat/tatcli/config" + "github.com/ovh/tat/tatcli/group" + "github.com/ovh/tat/tatcli/internal" + "github.com/ovh/tat/tatcli/message" + "github.com/ovh/tat/tatcli/presence" + "github.com/ovh/tat/tatcli/stats" + "github.com/ovh/tat/tatcli/system" + "github.com/ovh/tat/tatcli/topic" + "github.com/ovh/tat/tatcli/ui" + "github.com/ovh/tat/tatcli/update" + "github.com/ovh/tat/tatcli/user" + "github.com/ovh/tat/tatcli/version" + "github.com/spf13/cobra" + "github.com/spf13/viper" +) + +var home = os.Getenv("HOME") + +var rootCmd = &cobra.Command{ + Use: "tatcli", + Short: "Text And Tags - Command Line Tool", + Long: `Text And Tags - Command Line Tool`, +} + +func main() { + addCommands() + rootCmd.PersistentFlags().BoolVarP(&internal.Verbose, "verbose", "v", false, "verbose output - display response from tat engine") + rootCmd.PersistentFlags().BoolVarP(&internal.Debug, "debug", "", false, "debug output - display request and response") + rootCmd.PersistentFlags().BoolVarP(&internal.Pretty, "pretty", "t", false, "Pretty Print Json Output") + rootCmd.PersistentFlags().BoolVarP(&internal.ShowStackTrace, "showStackTrace", "", false, "Show Stack Trace if tatcli panic") + rootCmd.PersistentFlags().BoolVarP(&internal.SSLInsecureSkipVerify, "sslInsecureSkipVerify", "l", false, "Skip certificate check with SSL connection") + rootCmd.PersistentFlags().StringVarP(&internal.URL, "url", "", "", "URL Tat Engine, facultative if you have a "+home+"/.tatcli/config.json file") + rootCmd.PersistentFlags().StringVarP(&internal.TatwebuiURL, "tatwebui-url", "", "", "URL of Tat WebUI, facultative") + rootCmd.PersistentFlags().StringVarP(&internal.Username, "username", "u", "", "username, facultative if you have a "+home+"/.tatcli/config.json file") + rootCmd.PersistentFlags().StringVarP(&internal.Password, "password", "p", "", "password, facultative if you have a "+home+"/.tatcli/config.json file") + rootCmd.PersistentFlags().StringVarP(&internal.ConfigFile, "configFile", "c", home+"/.tatcli/config.json", "configuration file, default is "+home+"/.tatcli/config.json") + + viper.BindPFlag("url", rootCmd.PersistentFlags().Lookup("url")) + viper.BindPFlag("tatwebui-url", rootCmd.PersistentFlags().Lookup("tatwebui-url")) + viper.BindPFlag("username", rootCmd.PersistentFlags().Lookup("username")) + viper.BindPFlag("password", rootCmd.PersistentFlags().Lookup("password")) + + if err := rootCmd.Execute(); err != nil { + fmt.Println(err) + os.Exit(-1) + } +} + +//AddCommands adds child commands to the root command rootCmd. +func addCommands() { + rootCmd.AddCommand(config.Cmd) + rootCmd.AddCommand(group.Cmd) + rootCmd.AddCommand(message.Cmd) + rootCmd.AddCommand(presence.Cmd) + rootCmd.AddCommand(stats.Cmd) + rootCmd.AddCommand(topic.Cmd) + rootCmd.AddCommand(update.Cmd) + rootCmd.AddCommand(user.Cmd) + rootCmd.AddCommand(ui.Cmd) + rootCmd.AddCommand(system.Cmd) + rootCmd.AddCommand(version.Cmd) +} diff --git a/tatcli/message/add.go b/tatcli/message/add.go new file mode 100644 index 0000000..26e2e3d --- /dev/null +++ b/tatcli/message/add.go @@ -0,0 +1,61 @@ +package message + +import ( + "fmt" + "strings" + + "github.com/ovh/tat" + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" +) + +var cmdLabel []string + +var ( + dateCreation int +) + +func init() { + cmdMessageAdd.Flags().IntVarP(&dateCreation, "dateCreation", "", -1, "Force date creation, only for system user") + cmdMessageAdd.Flags().StringSliceVar(&cmdLabel, "label", nil, "add labels : --label=\"#EEEE;myLabel1,#EEEE;myLabel2\"") +} + +var cmdMessageAdd = &cobra.Command{ + Use: "add", + Aliases: []string{"a"}, + Short: "tatcli message add [--dateCreation=timestamp] ", + Long: `Add a message to a Topic: + tatcli message add /Private/firstname.lastname my new messsage + `, + Run: func(cmd *cobra.Command, args []string) { + if len(args) >= 2 { + topic := args[0] + message := strings.Join(args[1:], " ") + msg, err := Create(topic, message) + internal.Check(err) + if internal.Verbose { + internal.Print(msg) + } + } else { + internal.Exit("Invalid argument to add a message: tatcli msg add --help\n") + } + }, +} + +// Create creates a message in specified topic +func Create(topic, message string) (*tat.MessageJSONOut, error) { + m := tat.MessageJSON{Text: message, Topic: topic} + if dateCreation > 0 { + m.DateCreation = float64(dateCreation) + } + for _, label := range cmdLabel { + s := strings.Split(label, ";") + if len(s) == 2 { + m.Labels = append(m.Labels, tat.Label{Text: s[1], Color: s[0]}) + } else { + return nil, fmt.Errorf("Invalid argument label %s to add a message: tatcli msg add --help\n", label) + } + } + + return internal.Client().MessageAdd(m) +} diff --git a/tatcli/message/concat.go b/tatcli/message/concat.go new file mode 100644 index 0000000..040a5b5 --- /dev/null +++ b/tatcli/message/concat.go @@ -0,0 +1,31 @@ +package message + +import ( + "strings" + + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" +) + +var cmdMessageConcat = &cobra.Command{ + Use: "concat", + Short: "Update a message (if it's enabled on topic) by adding additional text at the end of message: tatcli message concat ", + Long: `Update a message: + It could be used to add tag or text at the end of one message. + tatcli message concat + `, + Run: func(cmd *cobra.Command, args []string) { + if len(args) >= 3 { + topic := args[0] + idMessage := args[1] + addText := strings.Join(args[2:], " ") + out, err := internal.Client().MessageConcat(topic, idMessage, addText) + internal.Check(err) + if internal.Verbose { + internal.Print(out) + } + } else { + internal.Exit("Invalid argument to update a message: tatcli message concat --help\n") + } + }, +} diff --git a/tatcli/message/delete.go b/tatcli/message/delete.go new file mode 100644 index 0000000..8a4e98c --- /dev/null +++ b/tatcli/message/delete.go @@ -0,0 +1,30 @@ +package message + +import ( + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" +) + +var cascade, cascadeForce bool + +func init() { + cmdMessageDelete.Flags().BoolVarP(&cascade, "cascade", "", false, "--cascade : delete message and its replies") + cmdMessageDelete.Flags().BoolVarP(&cascadeForce, "cascadeForce", "", false, "--cascadeForce : delete message and its replies, event if it's in a Tasks Topic of one user") +} + +var cmdMessageDelete = &cobra.Command{ + Use: "delete", + Aliases: []string{"rm"}, + Short: "Delete a message: tatcli message delete [--cascade] [--cascadeForce]", + Run: func(cmd *cobra.Command, args []string) { + if len(args) == 2 { + out, err := internal.Client().MessageDelete(args[1], args[0], cascade, cascadeForce) + internal.Check(err) + if internal.Verbose { + internal.Print(out) + } + } else { + internal.Exit("Invalid argument to delete message: tatcli message delete --help\n") + } + }, +} diff --git a/tatcli/message/delete_bulk.go b/tatcli/message/delete_bulk.go new file mode 100644 index 0000000..44de80c --- /dev/null +++ b/tatcli/message/delete_bulk.go @@ -0,0 +1,69 @@ +package message + +import ( + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" +) + +func init() { + cmdMessageDeleteBulk.Flags().BoolVarP(&cascade, "cascade", "", false, "--cascade : delete messages and replies") + cmdMessageDeleteBulk.Flags().BoolVarP(&cascadeForce, "cascadeForce", "", false, "--cascadeForce : delete messages and replies, event if it's in a Tasks Topic of one user") + + cmdMessageDeleteBulk.Flags().StringVarP(&criteria.IDMessage, "idMessage", "", "", "Search by IDMessage") + cmdMessageDeleteBulk.Flags().StringVarP(&criteria.InReplyOfID, "inReplyOfID", "", "", "Search by IDMessage InReply") + cmdMessageDeleteBulk.Flags().StringVarP(&criteria.InReplyOfIDRoot, "inReplyOfIDRoot", "", "", "Search by IDMessage IdRoot") + cmdMessageDeleteBulk.Flags().StringVarP(&criteria.AllIDMessage, "allIDMessage", "", "", "Search in All ID Message (idMessage, idReply, idRoot)") + cmdMessageDeleteBulk.Flags().StringVarP(&criteria.Text, "text", "", "", "Search by text") + cmdMessageDeleteBulk.Flags().StringVarP(&criteria.Topic, "topic", "", "", "Search by topic") + cmdMessageDeleteBulk.Flags().StringVarP(&criteria.Label, "label", "", "", "Search by label: could be labelA,labelB") + cmdMessageDeleteBulk.Flags().StringVarP(&criteria.NotLabel, "notLabel", "", "", "Search by label (exclude): could be labelA,labelB") + cmdMessageDeleteBulk.Flags().StringVarP(&criteria.AndLabel, "andLabel", "", "", "Search by label (and) : could be labelA,labelB") + cmdMessageDeleteBulk.Flags().StringVarP(&criteria.Tag, "tag", "", "", "Search by tag : could be tagA,tagB") + cmdMessageDeleteBulk.Flags().StringVarP(&criteria.NotTag, "notTag", "", "", "Search by tag (exclude) : could be tagA,tagB") + cmdMessageDeleteBulk.Flags().StringVarP(&criteria.AndTag, "andTag", "", "", "Search by tag (and) : could be tagA,tagB") + cmdMessageDeleteBulk.Flags().StringVarP(&criteria.DateMinCreation, "dateMinCreation", "", "", "Search by dateCreation (timestamp), select messages where dateCreation >= dateMinCreation") + cmdMessageDeleteBulk.Flags().StringVarP(&criteria.DateMaxCreation, "dateMaxCreation", "", "", "Search by dateCreation (timestamp), select messages where dateCreation <= dateMaxCreation") + cmdMessageDeleteBulk.Flags().StringVarP(&criteria.DateMinUpdate, "dateMinUpdate", "", "", "Search by dateUpdate (timestamp), select messages where dateUpdate >= dateMinUpdate") + cmdMessageDeleteBulk.Flags().StringVarP(&criteria.DateMaxUpdate, "dateMaxUpdate", "", "", "Search by dateUpdate (timestamp), select messages where dateUpdate <= dateMaxUpdate") + cmdMessageDeleteBulk.Flags().StringVarP(&criteria.DateRefCreation, "dateRefCreation", "", "", "This have to be used with dateRefDeltaMinCreation and / or dateRefDeltaMaxCreation. This could be BeginningOfMinute, BeginningOfHour, BeginningOfDay, BeginningOfWeek, BeginningOfMonth, BeginningOfQuarter, BeginningOfYear") + cmdMessageDeleteBulk.Flags().StringVarP(&criteria.DateRefDeltaMinCreation, "dateRefDeltaMinCreation", "", "", "Add seconds to dateRefCreation flag") + cmdMessageDeleteBulk.Flags().StringVarP(&criteria.DateRefDeltaMaxCreation, "dateRefDeltaMaxCreation", "", "", "Add seconds to dateRefCreation flag") + cmdMessageDeleteBulk.Flags().StringVarP(&criteria.DateRefUpdate, "dateRefUpdate", "", "", "This have to be used with dateRefDeltaMinUpdate and / or dateRefDeltaMaxUpdate. This could be BeginningOfMinute, BeginningOfHour, BeginningOfDay, BeginningOfWeek, BeginningOfMonth, BeginningOfQuarter, BeginningOfYear") + cmdMessageDeleteBulk.Flags().StringVarP(&criteria.DateRefDeltaMinUpdate, "dateRefDeltaMinUpdate", "", "", "Add seconds to dateRefUpdate flag") + cmdMessageDeleteBulk.Flags().StringVarP(&criteria.DateRefDeltaMaxUpdate, "dateRefDeltaMaxUpdate", "", "", "Add seconds to dateRefUpdate flag") + cmdMessageDeleteBulk.Flags().StringVarP(&criteria.LastMinCreation, "lastMinCreation", "", "", "Search by dateCreation (duration in second), select messages where dateCreation >= now - lastMinCreation") + cmdMessageDeleteBulk.Flags().StringVarP(&criteria.LastMaxCreation, "lastMaxCreation", "", "", "Search by dateCreation (duration in second), select messages where dateCreation <= now - lastMaxCreation") + cmdMessageDeleteBulk.Flags().StringVarP(&criteria.LastMinUpdate, "lastMinUpdate", "", "", "Search by dateUpdate (duration in second), select messages where dateUpdate >= now - lastMinCreation") + cmdMessageDeleteBulk.Flags().StringVarP(&criteria.LastMaxUpdate, "lastMaxUpdate", "", "", "Search by dateUpdate (duration in second), select messages where dateUpdate <= now - lastMaxCreation") + cmdMessageDeleteBulk.Flags().StringVarP(&criteria.LastHourMinCreation, "lastHourMinCreation", "", "", "Search by dateCreation, select messages where dateCreation >= Now Beginning Of Hour - (60 * lastHourMinCreation)") + cmdMessageDeleteBulk.Flags().StringVarP(&criteria.LastHourMaxCreation, "lastHourMaxCreation", "", "", "Search by dateCreation, select messages where dateCreation <= Now Beginning Of Hour - (60 * lastHourMaxCreation)") + cmdMessageDeleteBulk.Flags().StringVarP(&criteria.LastHourMinUpdate, "lastHourMinUpdate", "", "", "Search by dateUpdate, select messages where dateUpdate >= Now Beginning Of Hour - (60 * lastHourMinCreation)") + cmdMessageDeleteBulk.Flags().StringVarP(&criteria.LastHourMaxUpdate, "lastHourMaxUpdate", "", "", "Search by dateUpdate, select messages where dateUpdate <= Now Beginning Of Hour - (60 * lastHourMaxCreation)") + cmdMessageDeleteBulk.Flags().StringVarP(&criteria.Username, "username", "", "", "Search by username : could be usernameA,usernameB") + cmdMessageDeleteBulk.Flags().StringVarP(&criteria.LimitMinNbReplies, "limitMinNbReplies", "", "", "In onetree mode, filter root messages with more or equals minNbReplies") + cmdMessageDeleteBulk.Flags().StringVarP(&criteria.LimitMaxNbReplies, "limitMaxNbReplies", "", "", "In onetree mode, filter root messages with min or equals maxNbReplies") + cmdMessageDeleteBulk.Flags().StringVarP(&criteria.LimitMinNbVotesUP, "limitMinNbVotesUP", "", "", "Search by nbVotesUP") + cmdMessageDeleteBulk.Flags().StringVarP(&criteria.LimitMaxNbVotesUP, "limitMaxNbVotesUP", "", "", "Search by nbVotesUP") + cmdMessageDeleteBulk.Flags().StringVarP(&criteria.LimitMinNbVotesDown, "limitMinNbVotesDown", "", "", "Search by nbVotesDown") + cmdMessageDeleteBulk.Flags().StringVarP(&criteria.LimitMaxNbVotesDown, "limitMaxNbVotesDown", "", "", "Search by nbVotesDown") + cmdMessageDeleteBulk.Flags().StringVarP(&criteria.OnlyMsgRoot, "onlyMsgRoot", "", "", "--onlyMsgRoot=true: restricts to root message only (inReplyOfIDRoot empty). If treeView is used, limit search criteria to root message, replies are still given, independently of search criteria.") + cmdMessageDeleteBulk.Flags().StringVarP(&criteria.OnlyCount, "onlyCount", "", "", "--onlyCount=true: only count messages, without retrieve msg. limit, skip, treeview criterias are ignored.") + cmdMessageDeleteBulk.Flags().StringVarP(&criteria.TreeView, "treeView", "", "", "Tree View of messages: onetree or fulltree. Default: onetree") +} + +var cmdMessageDeleteBulk = &cobra.Command{ + Use: "deletebulk", + Short: "Delete a list of messages: tatcli message deletebulk [--cascade] [--cascadeForce]", + Run: func(cmd *cobra.Command, args []string) { + if len(args) >= 1 { + criteria.Skip, criteria.Limit = internal.GetSkipLimit(args) + out, err := internal.Client().MessagesDeleteBulk(args[0], cascade, cascadeForce, criteria) + internal.Check(err) + if internal.Verbose { + internal.Print(out) + } + } else { + internal.Exit("Invalid argument to delete message: tatcli message delete --help\n") + } + }, +} diff --git a/tatcli/message/label.go b/tatcli/message/label.go new file mode 100644 index 0000000..a714ec2 --- /dev/null +++ b/tatcli/message/label.go @@ -0,0 +1,37 @@ +package message + +import ( + "strings" + + "github.com/ovh/tat" + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" +) + +var cmdMessageLabel = &cobra.Command{ + Use: "label", + Short: "Add a label to a message: tatcli message label ", + Long: `Add a label to a message: + tatcli message label + Example in bash: + tatcli message label /MyTopic 56bde943968b970001bac20a \#EEEEEE my White Label + or works too: + tatcli message label /MyTopic 56bde943968b970001bac20a EEEEEE my White Label + `, + Run: func(cmd *cobra.Command, args []string) { + if len(args) >= 4 { + text := strings.Join(args[3:], " ") + color := args[2] + if !strings.HasPrefix(color, "#") { + color = "#" + color + } + out, err := internal.Client().MessageLabel(args[0], args[1], tat.Label{Text: text, Color: color}) + internal.Check(err) + if internal.Verbose { + internal.Print(out) + } + } else { + internal.Exit("Invalid argument to add a label: tatcli message label --help\n") + } + }, +} diff --git a/tatcli/message/like.go b/tatcli/message/like.go new file mode 100644 index 0000000..9d3b646 --- /dev/null +++ b/tatcli/message/like.go @@ -0,0 +1,22 @@ +package message + +import ( + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" +) + +var cmdMessageLike = &cobra.Command{ + Use: "like", + Short: "Like a message: tatcli message like ", + Run: func(cmd *cobra.Command, args []string) { + if len(args) == 2 { + out, err := internal.Client().MessageLike(args[0], args[1]) + internal.Check(err) + if internal.Verbose { + internal.Print(out) + } + } else { + internal.Exit("Invalid argument to like a message: tatcli message like --help\n") + } + }, +} diff --git a/tatcli/message/list.go b/tatcli/message/list.go new file mode 100644 index 0000000..2ac254e --- /dev/null +++ b/tatcli/message/list.go @@ -0,0 +1,145 @@ +package message + +import ( + "fmt" + "os/exec" + "strings" + "time" + + "github.com/briandowns/spinner" + + "github.com/ovh/tat" + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" +) + +var ( + criteria tat.MessageCriteria + stream bool + execMsg string +) + +func init() { + cmdMessageList.Flags().StringVarP(&criteria.TreeView, "treeView", "", "", "Tree View of messages: onetree or fulltree. Default: notree") + cmdMessageList.Flags().StringVarP(&criteria.IDMessage, "idMessage", "", "", "Search by IDMessage") + cmdMessageList.Flags().StringVarP(&criteria.InReplyOfID, "inReplyOfID", "", "", "Search by IDMessage InReply") + cmdMessageList.Flags().StringVarP(&criteria.InReplyOfIDRoot, "inReplyOfIDRoot", "", "", "Search by IDMessage IdRoot") + cmdMessageList.Flags().StringVarP(&criteria.AllIDMessage, "allIDMessage", "", "", "Search in All ID Message (idMessage, idReply, idRoot)") + cmdMessageList.Flags().StringVarP(&criteria.Text, "text", "", "", "Search by text") + cmdMessageList.Flags().StringVarP(&criteria.Topic, "topic", "", "", "Search by topic") + cmdMessageList.Flags().StringVarP(&criteria.Label, "label", "", "", "Search by label: could be labelA,labelB") + cmdMessageList.Flags().StringVarP(&criteria.StartLabel, "startLabel", "", "", "Search by a label prefix: --startLabel='mykey:,myKey2:'") + cmdMessageList.Flags().StringVarP(&criteria.NotLabel, "notLabel", "", "", "Search by label (exclude): could be labelA,labelB") + cmdMessageList.Flags().StringVarP(&criteria.AndLabel, "andLabel", "", "", "Search by label (and) : could be labelA,labelB") + cmdMessageList.Flags().StringVarP(&criteria.Tag, "tag", "", "", "Search by tag : could be tagA,tagB") + cmdMessageList.Flags().StringVarP(&criteria.StartTag, "startTag", "", "", "Search by a tag prefix: --startTag='mykey:,myKey2:'") + cmdMessageList.Flags().StringVarP(&criteria.NotTag, "notTag", "", "", "Search by tag (exclude) : could be tagA,tagB") + cmdMessageList.Flags().StringVarP(&criteria.AndTag, "andTag", "", "", "Search by tag (and) : could be tagA,tagB") + cmdMessageList.Flags().StringVarP(&criteria.DateMinCreation, "dateMinCreation", "", "", "Search by dateCreation (timestamp), select messages where dateCreation >= dateMinCreation") + cmdMessageList.Flags().StringVarP(&criteria.DateMaxCreation, "dateMaxCreation", "", "", "Search by dateCreation (timestamp), select messages where dateCreation <= dateMaxCreation") + cmdMessageList.Flags().StringVarP(&criteria.DateMinUpdate, "dateMinUpdate", "", "", "Search by dateUpdate (timestamp), select messages where dateUpdate >= dateMinUpdate") + cmdMessageList.Flags().StringVarP(&criteria.DateMaxUpdate, "dateMaxUpdate", "", "", "Search by dateUpdate (timestamp), select messages where dateUpdate <= dateMaxUpdate") + cmdMessageList.Flags().StringVarP(&criteria.DateRefCreation, "dateRefCreation", "", "", "This have to be used with dateRefDeltaMinCreation and / or dateRefDeltaMaxCreation. This could be BeginningOfMinute, BeginningOfHour, BeginningOfDay, BeginningOfWeek, BeginningOfMonth, BeginningOfQuarter, BeginningOfYear") + cmdMessageList.Flags().StringVarP(&criteria.DateRefDeltaMinCreation, "dateRefDeltaMinCreation", "", "", "Add seconds to dateRefCreation flag") + cmdMessageList.Flags().StringVarP(&criteria.DateRefDeltaMaxCreation, "dateRefDeltaMaxCreation", "", "", "Add seconds to dateRefCreation flag") + cmdMessageList.Flags().StringVarP(&criteria.DateRefUpdate, "dateRefUpdate", "", "", "This have to be used with dateRefDeltaMinUpdate and / or dateRefDeltaMaxUpdate. This could be BeginningOfMinute, BeginningOfHour, BeginningOfDay, BeginningOfWeek, BeginningOfMonth, BeginningOfQuarter, BeginningOfYear") + cmdMessageList.Flags().StringVarP(&criteria.DateRefDeltaMinUpdate, "dateRefDeltaMinUpdate", "", "", "Add seconds to dateRefUpdate flag") + cmdMessageList.Flags().StringVarP(&criteria.DateRefDeltaMaxUpdate, "dateRefDeltaMaxUpdate", "", "", "Add seconds to dateRefUpdate flag") + cmdMessageList.Flags().StringVarP(&criteria.LastMinCreation, "lastMinCreation", "", "", "Search by dateCreation (duration in second), select messages where dateCreation >= now - lastMinCreation") + cmdMessageList.Flags().StringVarP(&criteria.LastMaxCreation, "lastMaxCreation", "", "", "Search by dateCreation (duration in second), select messages where dateCreation <= now - lastMaxCreation") + cmdMessageList.Flags().StringVarP(&criteria.LastMinUpdate, "lastMinUpdate", "", "", "Search by dateUpdate (duration in second), select messages where dateUpdate >= now - lastMinCreation") + cmdMessageList.Flags().StringVarP(&criteria.LastMaxUpdate, "lastMaxUpdate", "", "", "Search by dateUpdate (duration in second), select messages where dateUpdate <= now - lastMaxCreation") + cmdMessageList.Flags().StringVarP(&criteria.LastHourMinCreation, "lastHourMinCreation", "", "", "Search by dateCreation, select messages where dateCreation >= Now Beginning Of Hour - (60 * lastHourMinCreation)") + cmdMessageList.Flags().StringVarP(&criteria.LastHourMaxCreation, "lastHourMaxCreation", "", "", "Search by dateCreation, select messages where dateCreation <= Now Beginning Of Hour - (60 * lastHourMaxCreation)") + cmdMessageList.Flags().StringVarP(&criteria.LastHourMinUpdate, "lastHourMinUpdate", "", "", "Search by dateUpdate, select messages where dateUpdate >= Now Beginning Of Hour - (60 * lastHourMinCreation)") + cmdMessageList.Flags().StringVarP(&criteria.LastHourMaxUpdate, "lastHourMaxUpdate", "", "", "Search by dateUpdate, select messages where dateUpdate <= Now Beginning Of Hour - (60 * lastHourMaxCreation)") + cmdMessageList.Flags().StringVarP(&criteria.Username, "username", "", "", "Search by username : could be usernameA,usernameB") + cmdMessageList.Flags().StringVarP(&criteria.LimitMinNbReplies, "limitMinNbReplies", "", "", "In onetree mode, filter root messages with more or equals minNbReplies") + cmdMessageList.Flags().StringVarP(&criteria.LimitMaxNbReplies, "limitMaxNbReplies", "", "", "In onetree mode, filter root messages with min or equals maxNbReplies") + cmdMessageList.Flags().StringVarP(&criteria.LimitMinNbVotesUP, "limitMinNbVotesUP", "", "", "Search by nbVotesUP") + cmdMessageList.Flags().StringVarP(&criteria.LimitMaxNbVotesUP, "limitMaxNbVotesUP", "", "", "Search by nbVotesUP") + cmdMessageList.Flags().StringVarP(&criteria.LimitMinNbVotesDown, "limitMinNbVotesDown", "", "", "Search by nbVotesDown") + cmdMessageList.Flags().StringVarP(&criteria.LimitMaxNbVotesDown, "limitMaxNbVotesDown", "", "", "Search by nbVotesDown") + cmdMessageList.Flags().StringVarP(&criteria.OnlyMsgRoot, "onlyMsgRoot", "", "", "--onlyMsgRoot=true: restricts to root message only (inReplyOfIDRoot empty). If treeView is used, limit search criteria to root message, replies are still given, independently of search criteria.") + cmdMessageList.Flags().StringVarP(&criteria.OnlyMsgReply, "onlyMsgReply", "", "", "--onlyMsgReply=true: restricts to reply message only (inReplyOfIDRoot not empty). If treeView is used, limit search criteria to reply, messages root are still given, independently of search criteria.") + cmdMessageList.Flags().StringVarP(&criteria.OnlyCount, "onlyCount", "", "", "--onlyCount=true: only count messages, without retrieve msg. limit, skip, treeview criterias are ignored.") + cmdMessageList.Flags().StringVarP(&criteria.SortBy, "sortBy", "", "", "--sortBy=-dateCreation: sort message. Use '-' to reverse sort. Default is --sortBy=-dateCreation. You can use: text, topic, inReplyOfID, inReplyOfIDRoot, nbLikes, labels, likers, votersUP, votersDown, nbVotesUP, nbVotesDown, userMentions, urls, tags, dateCreation, dateUpdate, author, nbReplies") + cmdMessageList.Flags().BoolVarP(&stream, "stream", "s", false, "stream messages --stream. Request tat each 10s, default sort: dateUpdate") + cmdMessageList.Flags().StringVarP(&execMsg, "exec", "", "", "exec a cmd on each new message: --exec 'myLights --pulse blue --duration=1000'") +} + +var cmdMessageList = &cobra.Command{ + Use: "list", + Short: "List all messages on one topic: tatcli msg list ", + Aliases: []string{"l"}, + Run: func(cmd *cobra.Command, args []string) { + if len(args) < 1 { + internal.Exit("Invalid argument to list message: See tatcli msg list --help\n") + } + + if stream { + cmdMessageListStream(args[0]) + return + } + + criteria.Skip, criteria.Limit = internal.GetSkipLimit(args) + c := internal.Client() + var err error + var out interface{} + if criteria.OnlyCount == tat.True { + out, err = c.MessageCount(args[0], &criteria) + } else { + out, err = c.MessageList(args[0], &criteria) + } + internal.Check(err) + internal.Print(out) + }, +} + +func cmdMessageListStream(topic string) { + c := internal.Client() + lastTime := float64(time.Now().Unix()) + lastID := "" + + for { + criteria.Skip = 0 + criteria.Limit = 10 + criteria.SortBy = "dateUpdate" + criteria.DateMinUpdate = fmt.Sprintf("%f", lastTime) + out, err := c.MessageList(topic, &criteria) + if err != nil { + fmt.Printf("Error:%s", err) + continue + } + + for _, m := range out.Messages { + if lastID != m.ID { + processMsg(m) + lastTime = m.DateUpdate + } + } + + // do not wait if request reach criteria.Limit + if len(out.Messages) < criteria.Limit { + time.Sleep(10 * time.Second) + } + } +} + +func processMsg(msg tat.Message) { + fmt.Printf("%s %s %s\n", time.Unix(int64(msg.DateUpdate), 0).Format(time.Stamp), msg.Author.Username, msg.Text) + opts := strings.Split(execMsg, " ") + if execMsg != "" { + s := spinner.New(spinner.CharSets[35], 100*time.Millisecond) + cmd := exec.Command(opts[0], opts[1:]...) + s.Start() + if err := cmd.Start(); err != nil { + fmt.Printf("Error: %s", err) + return + } + if err := cmd.Wait(); err != nil { + fmt.Printf("Error: %s\n", err) + } + s.Stop() + } +} diff --git a/tatcli/message/message.go b/tatcli/message/message.go new file mode 100644 index 0000000..1df63c9 --- /dev/null +++ b/tatcli/message/message.go @@ -0,0 +1,35 @@ +package message + +import ( + "github.com/spf13/cobra" +) + +func init() { + Cmd.AddCommand(cmdMessageAdd) + Cmd.AddCommand(cmdMessageReply) + Cmd.AddCommand(cmdMessageDelete) + Cmd.AddCommand(cmdMessageDeleteBulk) + Cmd.AddCommand(cmdMessageUpdate) + Cmd.AddCommand(cmdMessageConcat) + Cmd.AddCommand(cmdMessageMove) + Cmd.AddCommand(cmdMessageTask) + Cmd.AddCommand(cmdMessageUntask) + Cmd.AddCommand(cmdMessageLike) + Cmd.AddCommand(cmdMessageUnlike) + Cmd.AddCommand(cmdMessageVoteUP) + Cmd.AddCommand(cmdMessageVoteDown) + Cmd.AddCommand(cmdMessageUnVoteUP) + Cmd.AddCommand(cmdMessageUnVoteDown) + Cmd.AddCommand(cmdMessageLabel) + Cmd.AddCommand(cmdMessageUnlabel) + Cmd.AddCommand(cmdMessageRelabel) + Cmd.AddCommand(cmdMessageList) +} + +// Cmd message +var Cmd = &cobra.Command{ + Use: "message", + Short: "Manipulate messages: tatcli message --help", + Long: `Manipulate messages: tatcli message `, + Aliases: []string{"m", "msg"}, +} diff --git a/tatcli/message/move.go b/tatcli/message/move.go new file mode 100644 index 0000000..d35a640 --- /dev/null +++ b/tatcli/message/move.go @@ -0,0 +1,22 @@ +package message + +import ( + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" +) + +var cmdMessageMove = &cobra.Command{ + Use: "move", + Short: "Move a message: tatcli message move ", + Run: func(cmd *cobra.Command, args []string) { + if len(args) == 3 { + out, err := internal.Client().MessageMove(args[0], args[1], args[2]) + internal.Check(err) + if internal.Verbose { + internal.Print(out) + } + } else { + internal.Exit("Invalid argument to move a message: tatcli message move --help\n") + } + }, +} diff --git a/tatcli/message/relabel.go b/tatcli/message/relabel.go new file mode 100644 index 0000000..e9b2d6d --- /dev/null +++ b/tatcli/message/relabel.go @@ -0,0 +1,51 @@ +package message + +import ( + "strings" + + "github.com/ovh/tat" + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" +) + +var cmdOptions []string + +func init() { + cmdMessageRelabel.Flags().StringSliceVar(&cmdLabel, "label", nil, "add labels : --label=\"#EEEE;myLabel1,#EEEE;myLabel2\"") + cmdMessageRelabel.Flags().StringSliceVar(&cmdOptions, "options", nil, "remove only theses Labels on relabel : --options=\"myLabelToRemove1,myLabelToRemove2\"") +} + +var cmdMessageRelabel = &cobra.Command{ + Use: "relabel", + Short: "Remove all labels and add new ones to a message: tatcli msg relabel --label=\"#EEEE;myLabel1,#EEEE;myLabel2\" --options=\"myLabelToRemove1,myLabelToRemove2\"", + Long: `Remove all labels and add new ones to a message: + tatcli message relabel --label="#EEEE;myLabel1,#EEEE;myLabel2" + Example in bash: + tatcli message relabel /MyTopic 01234567890 --label="#EEEE;myLabel1,#EEEE;myLabel2" + + Only remove some labels : + + tatcli message relabel /MyTopic 01234567890 --label="#EEEE;myLabel1,#EEEE;myLabel2" --options="myLabelToRemove1,myLabelToRemove2" + + `, + Run: func(cmd *cobra.Command, args []string) { + if len(args) == 2 { + labels := []tat.Label{} + for _, label := range cmdLabel { + s := strings.Split(label, ";") + if len(s) == 2 { + labels = append(labels, tat.Label{Text: s[1], Color: s[0]}) + } else { + internal.Exit("Invalid argument label %s to 'relabel' a message: tatcli msg relabel --help\n", label) + } + } + out, err := internal.Client().MessageRelabel(args[0], args[1], labels, cmdOptions) + internal.Check(err) + if internal.Verbose { + internal.Print(out) + } + } else { + internal.Exit("Invalid argument to 'relabel': tatcli message relabel --help\n") + } + }, +} diff --git a/tatcli/message/reply.go b/tatcli/message/reply.go new file mode 100644 index 0000000..ed631be --- /dev/null +++ b/tatcli/message/reply.go @@ -0,0 +1,31 @@ +package message + +import ( + "strings" + + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" +) + +var cmdMessageReply = &cobra.Command{ + Use: "reply", + Aliases: []string{"r"}, + Short: "Reply to a message: tatcli message reply ", + Long: `Reply to a message: + tatcli message reply + `, + Run: func(cmd *cobra.Command, args []string) { + if len(args) >= 3 { + topic := args[0] + inReplyOfID := args[1] + message := strings.Join(args[2:], " ") + out, err := internal.Client().MessageReply(topic, inReplyOfID, message) + internal.Check(err) + if internal.Verbose { + internal.Print(out) + } + } else { + internal.Exit("Invalid argument to reply to a message: tatcli message reply --help\n") + } + }, +} diff --git a/tatcli/message/task.go b/tatcli/message/task.go new file mode 100644 index 0000000..657a43b --- /dev/null +++ b/tatcli/message/task.go @@ -0,0 +1,24 @@ +package message + +import ( + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" +) + +var cmdMessageTask = &cobra.Command{ + Use: "task", + Short: "Create a task from one message: tatcli message task /Private/username/tasks/sub-topic idMessage", + Long: `Create a task from one message: + tatcli message task /Private/username/tasks/sub-topic idMessage`, + Run: func(cmd *cobra.Command, args []string) { + if len(args) == 2 { + out, err := internal.Client().MessageTask(args[0], args[1]) + internal.Check(err) + if internal.Verbose { + internal.Print(out) + } + } else { + internal.Exit("Invalid argument to task a message: tatcli message task --help\n") + } + }, +} diff --git a/tatcli/message/unlabel.go b/tatcli/message/unlabel.go new file mode 100644 index 0000000..dc79ef2 --- /dev/null +++ b/tatcli/message/unlabel.go @@ -0,0 +1,25 @@ +package message + +import ( + "strings" + + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" +) + +var cmdMessageUnlabel = &cobra.Command{ + Use: "unlabel", + Short: "Remove a label from a message: tatcli message unlabel ", + Run: func(cmd *cobra.Command, args []string) { + if len(args) >= 3 { + label := strings.Join(args[2:], " ") + out, err := internal.Client().MessageUnlabel(args[0], args[1], label) + internal.Check(err) + if internal.Verbose { + internal.Print(out) + } + } else { + internal.Exit("Invalid argument to unlabel a message: tatcli message unlabel --help\n") + } + }, +} diff --git a/tatcli/message/unlike.go b/tatcli/message/unlike.go new file mode 100644 index 0000000..aca286f --- /dev/null +++ b/tatcli/message/unlike.go @@ -0,0 +1,22 @@ +package message + +import ( + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" +) + +var cmdMessageUnlike = &cobra.Command{ + Use: "unlike", + Short: "Unlike a message: tatcli message unlike ", + Run: func(cmd *cobra.Command, args []string) { + if len(args) == 2 { + out, err := internal.Client().MessageUnlike(args[0], args[1]) + internal.Check(err) + if internal.Verbose { + internal.Print(out) + } + } else { + internal.Exit("Invalid argument to unlike a message: tatcli message unlike --help\n") + } + }, +} diff --git a/tatcli/message/untask.go b/tatcli/message/untask.go new file mode 100644 index 0000000..3b9fada --- /dev/null +++ b/tatcli/message/untask.go @@ -0,0 +1,22 @@ +package message + +import ( + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" +) + +var cmdMessageUntask = &cobra.Command{ + Use: "untask", + Short: "Remove a message from tasks: tatcli message untask /Private/username/tasks idMessage", + Run: func(cmd *cobra.Command, args []string) { + if len(args) == 2 { + out, err := internal.Client().MessageUntask(args[0], args[1]) + internal.Check(err) + if internal.Verbose { + internal.Print(out) + } + } else { + internal.Exit("Invalid argument to untask a message: tatcli message untask --help\n") + } + }, +} diff --git a/tatcli/message/unvotedown.go b/tatcli/message/unvotedown.go new file mode 100644 index 0000000..fc9c353 --- /dev/null +++ b/tatcli/message/unvotedown.go @@ -0,0 +1,22 @@ +package message + +import ( + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" +) + +var cmdMessageUnVoteDown = &cobra.Command{ + Use: "unvotedown", + Short: "Remove a vote down from a message: tatcli message unvotedown ", + Run: func(cmd *cobra.Command, args []string) { + if len(args) == 2 { + out, err := internal.Client().MessageUnVoteDown(args[0], args[1]) + internal.Check(err) + if internal.Verbose { + internal.Print(out) + } + } else { + internal.Exit("Invalid argument to unvotedown a message: tatcli message unvotedown --help\n") + } + }, +} diff --git a/tatcli/message/unvoteup.go b/tatcli/message/unvoteup.go new file mode 100644 index 0000000..da11bc3 --- /dev/null +++ b/tatcli/message/unvoteup.go @@ -0,0 +1,22 @@ +package message + +import ( + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" +) + +var cmdMessageUnVoteUP = &cobra.Command{ + Use: "unvoteup", + Short: "Remove a vote UP from a message: tatcli message unvoteup ", + Run: func(cmd *cobra.Command, args []string) { + if len(args) == 2 { + out, err := internal.Client().MessageUnVoteUP(args[0], args[1]) + internal.Check(err) + if internal.Verbose { + internal.Print(out) + } + } else { + internal.Exit("Invalid argument to unvoteup a message: tatcli message unvoteup --help\n") + } + }, +} diff --git a/tatcli/message/update.go b/tatcli/message/update.go new file mode 100644 index 0000000..1742d76 --- /dev/null +++ b/tatcli/message/update.go @@ -0,0 +1,31 @@ +package message + +import ( + "strings" + + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" +) + +var cmdMessageUpdate = &cobra.Command{ + Use: "update", + Aliases: []string{"up"}, + Short: "Update a message (if it's enabled on topic): tatcli message update ", + Long: `Update a message: + tatcli message update + `, + Run: func(cmd *cobra.Command, args []string) { + if len(args) >= 3 { + topic := args[0] + idMessage := args[1] + message := strings.Join(args[2:], " ") + out, err := internal.Client().MessageUpdate(topic, idMessage, message) + internal.Check(err) + if internal.Verbose { + internal.Print(out) + } + } else { + internal.Exit("Invalid argument to update a message: tatcli message update --help\n") + } + }, +} diff --git a/tatcli/message/votedown.go b/tatcli/message/votedown.go new file mode 100644 index 0000000..6f67855 --- /dev/null +++ b/tatcli/message/votedown.go @@ -0,0 +1,22 @@ +package message + +import ( + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" +) + +var cmdMessageVoteDown = &cobra.Command{ + Use: "votedown", + Short: "Vote Down a message: tatcli message votedown ", + Run: func(cmd *cobra.Command, args []string) { + if len(args) == 1 { + out, err := internal.Client().MessageVoteDown(args[0], args[1]) + internal.Check(err) + if internal.Verbose { + internal.Print(out) + } + } else { + internal.Exit("Invalid argument to votedown a message: tatcli message votedown --help\n") + } + }, +} diff --git a/tatcli/message/voteup.go b/tatcli/message/voteup.go new file mode 100644 index 0000000..de102fd --- /dev/null +++ b/tatcli/message/voteup.go @@ -0,0 +1,22 @@ +package message + +import ( + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" +) + +var cmdMessageVoteUP = &cobra.Command{ + Use: "voteup", + Short: "Vote UP a message: tatcli message voteup ", + Run: func(cmd *cobra.Command, args []string) { + if len(args) == 1 { + out, err := internal.Client().MessageVoteUP(args[0], args[1]) + internal.Check(err) + if internal.Verbose { + internal.Print(out) + } + } else { + internal.Exit("Invalid argument to voteup a message: tatcli message voteup --help\n") + } + }, +} diff --git a/tatcli/package.sh b/tatcli/package.sh new file mode 100755 index 0000000..f45ae29 --- /dev/null +++ b/tatcli/package.sh @@ -0,0 +1,14 @@ +#!/bin/bash + +for GOOS in windows darwin linux freebsd; do + for GOARCH in 386 amd64 arm; do + if [[ $GOARCH == "arm" && $GOOS != "linux" ]]; then + continue; + fi; + architecture="${GOOS}-${GOARCH}" + echo "Building ${architecture} ${path}" + export GOOS=$GOOS + export GOARCH=$GOARCH + go build -ldflags "-X ${PROJECT_PATH}/${PROJECT_NAME}/update.architecture=${architecture} -X ${PROJECT_PATH}/${PROJECT_NAME}/update.urlUpdateSnapshot=${URL_UPDATE_SNAPSHOT}" -o bin/tatcli-${architecture} + done +done diff --git a/tatcli/presence/add.go b/tatcli/presence/add.go new file mode 100644 index 0000000..baca2fd --- /dev/null +++ b/tatcli/presence/add.go @@ -0,0 +1,25 @@ +package presence + +import ( + "strings" + + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" +) + +var cmdPresenceAdd = &cobra.Command{ + Use: "add", + Short: "Add a new presence on one topic with status (online, offline, busy): tatcli presence add ", + Run: func(cmd *cobra.Command, args []string) { + if len(args) == 2 { + status := strings.Join(args[1:], " ") + out, err := internal.Client().PresenceAddAndGet(args[0], status) + internal.Check(err) + if internal.Verbose { + internal.Print(out) + } + } else { + internal.Exit("Invalid argument: tatcli presence add --help\n") + } + }, +} diff --git a/tatcli/presence/delete.go b/tatcli/presence/delete.go new file mode 100644 index 0000000..0e9caab --- /dev/null +++ b/tatcli/presence/delete.go @@ -0,0 +1,19 @@ +package presence + +import ( + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" +) + +var cmdPresenceDelete = &cobra.Command{ + Use: "delete", + Short: "Delete a user's presence on one topic: tatcli presence delete ", + Run: func(cmd *cobra.Command, args []string) { + if len(args) == 2 { + err := internal.Client().PresenceDelete(args[0], args[1]) + internal.Check(err) + } else { + internal.Exit("Invalid argument: tatcli presence delete --help\n") + } + }, +} diff --git a/tatcli/presence/list.go b/tatcli/presence/list.go new file mode 100644 index 0000000..1f72da9 --- /dev/null +++ b/tatcli/presence/list.go @@ -0,0 +1,21 @@ +package presence + +import ( + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" +) + +var cmdPresenceList = &cobra.Command{ + Use: "list", + Short: "List all presences on one topic: tatcli presence list [] []", + Run: func(cmd *cobra.Command, args []string) { + if len(args) >= 1 { + skip, limit := internal.GetSkipLimit(args) + out, err := internal.Client().PresenceList(args[0], skip, limit) + internal.Check(err) + internal.Print(out) + } else { + internal.Exit("Invalid argument: tatcli presence list --help\n") + } + }, +} diff --git a/tatcli/presence/presence.go b/tatcli/presence/presence.go new file mode 100644 index 0000000..10b06a5 --- /dev/null +++ b/tatcli/presence/presence.go @@ -0,0 +1,17 @@ +package presence + +import "github.com/spf13/cobra" + +func init() { + Cmd.AddCommand(cmdPresenceAdd) + Cmd.AddCommand(cmdPresenceDelete) + Cmd.AddCommand(cmdPresenceList) +} + +// Cmd presence +var Cmd = &cobra.Command{ + Use: "presence", + Short: "Presence commands: tatcli presence --help", + Long: `Presence commands: tatcli presence []`, + Aliases: []string{"p"}, +} diff --git a/tatcli/release.sh b/tatcli/release.sh new file mode 100755 index 0000000..3985cb6 --- /dev/null +++ b/tatcli/release.sh @@ -0,0 +1,49 @@ +#!/bin/bash + +# +# Tag release and push to origin remotes. +# + +if [ $# -ne 1 ] +then + echo "Tag and push master to 'origin' remotes" + echo "Usage: `basename $0` version" + exit 1 +fi + +version="$1" +current_branch=`git rev-parse --abbrev-ref HEAD` + +# Check we are on master branch +if [ "$current_branch" != "master" ] +then + echo -e "$0 only works from *master* branch. When ready, Please run \n\tgit checkout master\n\t$0" + exit 1 +fi + +# Check there is no pending changes --> branch is clean +if [ -n "`git status --porcelain`" ] +then + echo "There are pending/uncommited changes in current branch." + echo "Please commit or stash them." + exit 1 +fi + +# Ensure commit is tagged and annotated +current_tag=$(git describe --exact-match 2>/dev/null) +if [ -n "$current_tag" ] +then + if [ "$current_tag" != "v$version" ] + then + echo "Error: version mismatch '$current_tag' != 'v$version'" + fi +else + sed -i.bak "s/const VERSION =.*/const VERSION = \"$version\"/g" internal/version.go + rm -f internal/version.go.bak + git commit -am "[auto] bump version to v$version" + git tag -s "v$version" +fi + +echo "Pushing master and 'v$version'" +git push origin master +git push origin "v$version" diff --git a/tatcli/stats/count.go b/tatcli/stats/count.go new file mode 100644 index 0000000..9f5976b --- /dev/null +++ b/tatcli/stats/count.go @@ -0,0 +1,21 @@ +package stats + +import ( + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" +) + +var cmdStatsCount = &cobra.Command{ + Use: "count", + Short: "Count all messages, groups, presences, users, groups, topics: tatcli stats count", + Run: func(cmd *cobra.Command, args []string) { + if len(args) >= 1 { + internal.Exit("Invalid argument: tatcli stats count --help\n") + cmd.Usage() + } else { + out, err := internal.Client().StatsCount() + internal.Check(err) + internal.Print(out) + } + }, +} diff --git a/tatcli/stats/db_collections.go b/tatcli/stats/db_collections.go new file mode 100644 index 0000000..3604190 --- /dev/null +++ b/tatcli/stats/db_collections.go @@ -0,0 +1,21 @@ +package stats + +import ( + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" +) + +var cmdStatsDBCollections = &cobra.Command{ + Use: "dbCollections", + Short: "DB Stats on each collection: tatcli stats dbCollections", + Run: func(cmd *cobra.Command, args []string) { + if len(args) >= 1 { + internal.Exit("Invalid argument: tatcli stats dbCollections --help\n") + cmd.Usage() + } else { + out, err := internal.Client().StatsDBCollections() + internal.Check(err) + internal.Print(out) + } + }, +} diff --git a/tatcli/stats/db_replset_config.go b/tatcli/stats/db_replset_config.go new file mode 100644 index 0000000..92366d3 --- /dev/null +++ b/tatcli/stats/db_replset_config.go @@ -0,0 +1,21 @@ +package stats + +import ( + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" +) + +var cmdStatsDBReplSetGetConfig = &cobra.Command{ + Use: "dbReplSetGetConfig", + Short: "DB Stats: tatcli stats dbReplSetGetConfig", + Run: func(cmd *cobra.Command, args []string) { + if len(args) >= 1 { + internal.Exit("Invalid argument: tatcli stats dbReplSetGetConfig --help\n") + cmd.Usage() + } else { + out, err := internal.Client().StatsDBReplSetGetConfig() + internal.Check(err) + internal.Print(out) + } + }, +} diff --git a/tatcli/stats/db_replset_status.go b/tatcli/stats/db_replset_status.go new file mode 100644 index 0000000..caeae4a --- /dev/null +++ b/tatcli/stats/db_replset_status.go @@ -0,0 +1,21 @@ +package stats + +import ( + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" +) + +var cmdStatsDBReplSetGetStatus = &cobra.Command{ + Use: "dbReplSetGetStatus", + Short: "DB Stats: tatcli stats dbReplSetGetStatus", + Run: func(cmd *cobra.Command, args []string) { + if len(args) >= 1 { + internal.Exit("Invalid argument: tatcli stats dbReplSetGetStatus --help\n") + cmd.Usage() + } else { + out, err := internal.Client().StatsDBReplSetGetStatus() + internal.Check(err) + internal.Print(out) + } + }, +} diff --git a/tatcli/stats/db_server_status.go b/tatcli/stats/db_server_status.go new file mode 100644 index 0000000..6037149 --- /dev/null +++ b/tatcli/stats/db_server_status.go @@ -0,0 +1,21 @@ +package stats + +import ( + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" +) + +var cmdStatsDBServerStatus = &cobra.Command{ + Use: "dbServerStatus", + Short: "DB Stats: tatcli stats dbServerStatus", + Run: func(cmd *cobra.Command, args []string) { + if len(args) >= 1 { + internal.Exit("Invalid argument: tatcli stats dbServerStatus --help\n") + cmd.Usage() + } else { + out, err := internal.Client().StatsDBServerStatus() + internal.Check(err) + internal.Print(out) + } + }, +} diff --git a/tatcli/stats/db_slowest_queries.go b/tatcli/stats/db_slowest_queries.go new file mode 100644 index 0000000..1fb5c27 --- /dev/null +++ b/tatcli/stats/db_slowest_queries.go @@ -0,0 +1,21 @@ +package stats + +import ( + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" +) + +var cmdStatsDBSlowestQueries = &cobra.Command{ + Use: "dbSlowestQueries", + Short: "DB Stats slowest Queries: tatcli stats dbSlowestQueries", + Run: func(cmd *cobra.Command, args []string) { + if len(args) >= 1 { + internal.Exit("Invalid argument: tatcli stats dbSlowestQueriess --help\n") + cmd.Usage() + } else { + out, err := internal.Client().StatsDBSlowestQueries() + internal.Check(err) + internal.Print(out) + } + }, +} diff --git a/tatcli/stats/db_stats.go b/tatcli/stats/db_stats.go new file mode 100644 index 0000000..dd8a3ff --- /dev/null +++ b/tatcli/stats/db_stats.go @@ -0,0 +1,20 @@ +package stats + +import ( + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" +) + +var cmdStatsDBStats = &cobra.Command{ + Use: "dbstats", + Short: "DB Stats: tatcli stats dbstats", + Run: func(cmd *cobra.Command, args []string) { + if len(args) >= 1 { + internal.Exit("Invalid argument: tatcli stats db --help\n") + } else { + out, err := internal.Client().StatsDBStats() + internal.Check(err) + internal.Print(out) + } + }, +} diff --git a/tatcli/stats/distribution_topics.go b/tatcli/stats/distribution_topics.go new file mode 100644 index 0000000..5cd3bee --- /dev/null +++ b/tatcli/stats/distribution_topics.go @@ -0,0 +1,75 @@ +package stats + +import ( + "fmt" + "os" + "sort" + "strconv" + + "github.com/olekukonko/tablewriter" + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" + "gopkg.in/cheggaaa/pb.v1" + + "github.com/ovh/tat" +) + +var minCount int +var withDedicated bool + +func init() { + cmdStatsDistribution.Flags().IntVar(&minCount, "minCount", -1, "Display topic with min count") + cmdStatsDistribution.Flags().BoolVar(&withDedicated, "withDedicated", true, "Hide dedicated topic") +} + +var cmdStatsDistribution = &cobra.Command{ + Use: "distributiontopics", + Short: "Distribution of messages per topics: tatcli stats distributiontopics", + Run: func(cmd *cobra.Command, args []string) { + b, errs := internal.Client().StatsDistributionTopics(0, 1) + internal.Check(errs) + + topics := []tat.TopicDistributionJSON{} + skip := 0 + limit := 10 + bar := pb.StartNew(b.Total) + for skip < b.Total { + out, err := internal.Client().StatsDistributionTopics(skip, limit) + internal.Check(err) + topics = append(topics, out.Topics...) + skip += 10 + bar.Set(skip) + } + + sort.Sort(byCount(topics)) + + data := [][]string{} + for _, t := range topics { + if minCount > 0 && t.Count < minCount { + continue + } + if !withDedicated && t.Dedicated { + continue + } + data = append(data, []string{t.Topic, strconv.Itoa(t.Count), fmt.Sprintf("%t", t.Dedicated)}) + } + + table := tablewriter.NewWriter(os.Stdout) + table.SetHeader([]string{"Topic", "Count", "Dedicated"}) + + for _, v := range data { + table.Append(v) + } + + bar.Finish() + + table.Render() + + }, +} + +type byCount []tat.TopicDistributionJSON + +func (a byCount) Len() int { return len(a) } +func (a byCount) Swap(i, j int) { a[i], a[j] = a[j], a[i] } +func (a byCount) Less(i, j int) bool { return a[i].Count < a[j].Count } diff --git a/tatcli/stats/instance.go b/tatcli/stats/instance.go new file mode 100644 index 0000000..de7820c --- /dev/null +++ b/tatcli/stats/instance.go @@ -0,0 +1,21 @@ +package stats + +import ( + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" +) + +var cmdStatsInstance = &cobra.Command{ + Use: "instance", + Short: "Info about current instance of engine", + Run: func(cmd *cobra.Command, args []string) { + if len(args) >= 1 { + internal.Exit("Invalid argument: tatcli stats instance --help\n") + cmd.Usage() + } else { + out, err := internal.Client().StatsInstance() + internal.Check(err) + internal.Print(out) + } + }, +} diff --git a/tatcli/stats/stats.go b/tatcli/stats/stats.go new file mode 100644 index 0000000..e42cfe8 --- /dev/null +++ b/tatcli/stats/stats.go @@ -0,0 +1,23 @@ +package stats + +import "github.com/spf13/cobra" + +func init() { + Cmd.AddCommand(cmdStatsCount) + Cmd.AddCommand(cmdStatsDistribution) + Cmd.AddCommand(cmdStatsDBStats) + Cmd.AddCommand(cmdStatsDBServerStatus) + Cmd.AddCommand(cmdStatsDBReplSetGetConfig) + Cmd.AddCommand(cmdStatsDBReplSetGetStatus) + Cmd.AddCommand(cmdStatsDBCollections) + Cmd.AddCommand(cmdStatsDBSlowestQueries) + Cmd.AddCommand(cmdStatsInstance) +} + +// Cmd command +var Cmd = &cobra.Command{ + Use: "stats", + Short: "Stats commands (admin only): tatcli stats --help", + Long: `Stats commands (admin only): tatcli stats []`, + Aliases: []string{"stat"}, +} diff --git a/tatcli/system/cache_clean.go b/tatcli/system/cache_clean.go new file mode 100644 index 0000000..bf26748 --- /dev/null +++ b/tatcli/system/cache_clean.go @@ -0,0 +1,20 @@ +package system + +import ( + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" +) + +var cmdSystemCacheClean = &cobra.Command{ + Use: "cacheclean", + Short: "Clean Cache: tatcli system cacheclean", + Run: func(cmd *cobra.Command, args []string) { + if len(args) >= 1 { + internal.Exit("Invalid argument: tatcli system cacheclean --help\n") + } else { + out, err := internal.Client().SystemCacheClean() + internal.Check(err) + internal.Print(out) + } + }, +} diff --git a/tatcli/system/cache_info.go b/tatcli/system/cache_info.go new file mode 100644 index 0000000..063cec9 --- /dev/null +++ b/tatcli/system/cache_info.go @@ -0,0 +1,20 @@ +package system + +import ( + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" +) + +var cmdSystemCacheInfo = &cobra.Command{ + Use: "cacheinfo", + Short: "Info on Cache: tatcli system cacheinfo", + Run: func(cmd *cobra.Command, args []string) { + if len(args) >= 1 { + internal.Exit("Invalid argument: tatcli system cacheinfo --help\n") + } else { + out, err := internal.Client().SystemCacheInfo() + internal.Check(err) + internal.Print(out) + } + }, +} diff --git a/tatcli/system/system.go b/tatcli/system/system.go new file mode 100644 index 0000000..cf80479 --- /dev/null +++ b/tatcli/system/system.go @@ -0,0 +1,16 @@ +package system + +import "github.com/spf13/cobra" + +func init() { + Cmd.AddCommand(cmdSystemCacheClean) + Cmd.AddCommand(cmdSystemCacheInfo) +} + +// Cmd command +var Cmd = &cobra.Command{ + Use: "system", + Short: "System commands (admin only): tatcli system --help", + Long: `System commands (admin only): tatcli system []`, + Aliases: []string{"sys"}, +} diff --git a/tatcli/tests.sh b/tatcli/tests.sh new file mode 100755 index 0000000..b6748fb --- /dev/null +++ b/tatcli/tests.sh @@ -0,0 +1,68 @@ +#!/bin/bash + +set -e + +echo "building tatcli locally" +go build + +_tatcli () { + binary="./tatcli --configFile=$HOME/.tatcli/config.tat.integration.tests.admin.json" + if [ -z "$1" ] # Is parameter #1 zero length? + then + echo "Invalid use of _test" # No parameter passed. + exit 1; + fi + CMD="$binary $1"; + echo "Running ${CMD}"; + $CMD + if [ $? != 0 ]; then + echo "$CMD is failed"; + exit 1; + fi; + echo ""; + echo "Passed"; +} + +_title () { + echo "---------" + echo "$1"; + echo "---------" +} + +# TODO +_title "Testing tatcli config..." +_tatcli "config show" + +_title "Testing tatcli group..." +_tatcli "group list 0 2" + +_title "Testing tatcli message..." +_tatcli "message add /Private/tat.integration.tests.admin new message `date`" +_tatcli "message list /Private/tat.integration.tests.admin 0 1" + +_title "Testing tatcli presence..." +_tatcli "presence list /Private/tat.integration.tests.admin 0 2" + +_title "Testing tatcli socket..." +# enable ws option in tat engine to run this test _tatcli "socket dump" + +_title "Testing tatcli stats..." +_tatcli "stats count" + +_title "Testing tatcli topic..." +_tatcli "topic list 0 2" +_tatcli "msg list /Private/tat.integration.tests.admin --onlyCount=true" +_tatcli "topic truncate /Private/tat.integration.tests.admin --force" +_tatcli "msg list /Private/tat.integration.tests.admin --onlyCount=true" + + +_title "Testing tatcli user..." +_tatcli "user list 0 2" +_tatcli "user me" + +_title "Testing tatcli version..." +_tatcli "version" + +_title "All Tests OK" + +exit 0; diff --git a/tatcli/topic/add_admin_group.go b/tatcli/topic/add_admin_group.go new file mode 100644 index 0000000..0de8e95 --- /dev/null +++ b/tatcli/topic/add_admin_group.go @@ -0,0 +1,23 @@ +package topic + +import ( + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" +) + +func init() { + cmdTopicAddAdminGroup.Flags().BoolVarP(&recursive, "recursive", "r", false, "Apply Rights Admin recursively") +} + +var cmdTopicAddAdminGroup = &cobra.Command{ + Use: "addAdminGroup", + Short: "Add Admin Groups to a topic: tatcli topic addAdminGroup [--recursive] [groupname2]...", + Run: func(cmd *cobra.Command, args []string) { + if len(args) >= 2 { + err := internal.Client().TopicAddAdminGroups(args[0], args[1:], recursive) + internal.Check(err) + } else { + internal.Exit("Invalid argument: tatcli topic addAdminGroup --help\n") + } + }, +} diff --git a/tatcli/topic/add_admin_user.go b/tatcli/topic/add_admin_user.go new file mode 100644 index 0000000..20b8546 --- /dev/null +++ b/tatcli/topic/add_admin_user.go @@ -0,0 +1,23 @@ +package topic + +import ( + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" +) + +func init() { + cmdTopicAddAdminUser.Flags().BoolVarP(&recursive, "recursive", "r", false, "Apply Rights Admin recursively") +} + +var cmdTopicAddAdminUser = &cobra.Command{ + Use: "addAdminUser", + Short: "Add Admin Users to a topic: tatcli topic addAdminUser [--recursive] [username2]...", + Run: func(cmd *cobra.Command, args []string) { + if len(args) >= 2 { + err := internal.Client().TopicAddAdminUsers(args[0], args[1:], recursive) + internal.Check(err) + } else { + internal.Exit("Invalid argument: tatcli topic addAdminUser --help\n") + } + }, +} diff --git a/tatcli/topic/add_parameter.go b/tatcli/topic/add_parameter.go new file mode 100644 index 0000000..31fad64 --- /dev/null +++ b/tatcli/topic/add_parameter.go @@ -0,0 +1,35 @@ +package topic + +import ( + "strings" + + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" +) + +func init() { + cmdTopicAddParameter.Flags().BoolVarP(&recursive, "recursive", "r", false, "Add Parameter recursively") +} + +var cmdTopicAddParameter = &cobra.Command{ + Use: "addParameter", + Short: "Add Parameter to a topic: tatcli topic addParameter [--recursive] : [:]... ", + Run: func(cmd *cobra.Command, args []string) { + if len(args) >= 2 { + topicAddParameter(args[0], args[1:]) + } else { + internal.Exit("Invalid argument: tatcli topic addParameter --help\n") + } + }, +} + +func topicAddParameter(topic string, parameters []string) { + for _, param := range parameters { + parameterSplitted := strings.Split(param, ":") + if len(parameterSplitted) != 2 { + continue + } + _, err := internal.Client().TopicAddParameter(topic, parameterSplitted[0], parameterSplitted[1], recursive) + internal.Check(err) + } +} diff --git a/tatcli/topic/add_ro_group.go b/tatcli/topic/add_ro_group.go new file mode 100644 index 0000000..04c930d --- /dev/null +++ b/tatcli/topic/add_ro_group.go @@ -0,0 +1,23 @@ +package topic + +import ( + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" +) + +func init() { + cmdTopicAddRoGroup.Flags().BoolVarP(&recursive, "recursive", "r", false, "Apply Rights RO recursively") +} + +var cmdTopicAddRoGroup = &cobra.Command{ + Use: "addRoGroup", + Short: "Add Read Only Groups to a topic: tatcli topic addRoGroup [--recursive] []...", + Run: func(cmd *cobra.Command, args []string) { + if len(args) >= 2 { + err := internal.Client().TopicAddRoGroups(args[0], args[1:], recursive) + internal.Check(err) + } else { + internal.Exit("Invalid argument: tatcli topic addRoGroup --help\n") + } + }, +} diff --git a/tatcli/topic/add_ro_user.go b/tatcli/topic/add_ro_user.go new file mode 100644 index 0000000..3b8ae3b --- /dev/null +++ b/tatcli/topic/add_ro_user.go @@ -0,0 +1,23 @@ +package topic + +import ( + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" +) + +func init() { + cmdTopicAddRoUser.Flags().BoolVarP(&recursive, "recursive", "r", false, "Apply Rights RO recursively") +} + +var cmdTopicAddRoUser = &cobra.Command{ + Use: "addRoUser", + Short: "Add Read Only Users to a topic: tatcli topic addRoUser [--recursive] [username2]...", + Run: func(cmd *cobra.Command, args []string) { + if len(args) >= 2 { + err := internal.Client().TopicAddRoUsers(args[0], args[1:], recursive) + internal.Check(err) + } else { + internal.Exit("Invalid argument: tatcli topic addRoUser --help\n") + } + }, +} diff --git a/tatcli/topic/add_rw_group.go b/tatcli/topic/add_rw_group.go new file mode 100644 index 0000000..9597e0d --- /dev/null +++ b/tatcli/topic/add_rw_group.go @@ -0,0 +1,23 @@ +package topic + +import ( + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" +) + +func init() { + cmdTopicAddRwGroup.Flags().BoolVarP(&recursive, "recursive", "r", false, "Apply Rights RW recursively") +} + +var cmdTopicAddRwGroup = &cobra.Command{ + Use: "addRwGroup", + Short: "Add Read Write Groups to a topic: tatcli topic addRwGroup [--recursive] []...", + Run: func(cmd *cobra.Command, args []string) { + if len(args) >= 2 { + err := internal.Client().TopicAddRwGroups(args[0], args[1:], recursive) + internal.Check(err) + } else { + internal.Exit("Invalid argument: tatcli topic addRwGroup --help\n") + } + }, +} diff --git a/tatcli/topic/add_rw_user.go b/tatcli/topic/add_rw_user.go new file mode 100644 index 0000000..3f588dc --- /dev/null +++ b/tatcli/topic/add_rw_user.go @@ -0,0 +1,23 @@ +package topic + +import ( + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" +) + +func init() { + cmdTopicAddRwUser.Flags().BoolVarP(&recursive, "recursive", "r", false, "Apply Rights RW recursively") +} + +var cmdTopicAddRwUser = &cobra.Command{ + Use: "addRwUser", + Short: "Add Read Write Users to a topic: tatcli topic addRwUser [--recursive] [username2]...", + Run: func(cmd *cobra.Command, args []string) { + if len(args) >= 2 { + err := internal.Client().TopicAddRwUsers(args[0], args[1:], recursive) + internal.Check(err) + } else { + internal.Exit("Invalid argument: tatcli topic addRwUser --help\n") + } + }, +} diff --git a/tatcli/topic/all_compute_labels.go b/tatcli/topic/all_compute_labels.go new file mode 100644 index 0000000..7b8f869 --- /dev/null +++ b/tatcli/topic/all_compute_labels.go @@ -0,0 +1,18 @@ +package topic + +import ( + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" +) + +var cmdTopicAllComputeLabels = &cobra.Command{ + Use: "allcomputelabels", + Short: "Compute Labels on all topics, only for tat admin : tatcli topic allcomputelabels", + Run: func(cmd *cobra.Command, args []string) { + out, err := internal.Client().TopicAllComputeLabels() + internal.Check(err) + if internal.Verbose { + internal.Print(out) + } + }, +} diff --git a/tatcli/topic/all_compute_replies.go b/tatcli/topic/all_compute_replies.go new file mode 100644 index 0000000..b71d36a --- /dev/null +++ b/tatcli/topic/all_compute_replies.go @@ -0,0 +1,18 @@ +package topic + +import ( + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" +) + +var cmdTopicAllComputeReplies = &cobra.Command{ + Use: "allcomputereplies", + Short: "Compute Replies on all topics, only for tat admin : tatcli topic allcomputereplies", + Run: func(cmd *cobra.Command, args []string) { + out, err := internal.Client().TopicAllComputeReplies() + internal.Check(err) + if internal.Verbose { + internal.Print(out) + } + }, +} diff --git a/tatcli/topic/all_compute_tags.go b/tatcli/topic/all_compute_tags.go new file mode 100644 index 0000000..0f1e692 --- /dev/null +++ b/tatcli/topic/all_compute_tags.go @@ -0,0 +1,18 @@ +package topic + +import ( + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" +) + +var cmdTopicAllComputeTags = &cobra.Command{ + Use: "allcomputetags", + Short: "Compute Tags on all topics, only for tat admin : tatcli topic allcomputetags", + Run: func(cmd *cobra.Command, args []string) { + out, err := internal.Client().TopicAllComputeTags() + internal.Check(err) + if internal.Verbose { + internal.Print(out) + } + }, +} diff --git a/tatcli/topic/all_set_param.go b/tatcli/topic/all_set_param.go new file mode 100644 index 0000000..4135287 --- /dev/null +++ b/tatcli/topic/all_set_param.go @@ -0,0 +1,23 @@ +package topic + +import ( + "github.com/ovh/tat" + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" +) + +var cmdTopicAllSetParam = &cobra.Command{ + Use: "allsetparam", + Short: "Set a param for all topics, only for tat admin : tatcli topic allsetparam ", + Run: func(cmd *cobra.Command, args []string) { + if len(args) == 2 { + out, err := internal.Client().TopicAllSetParam(tat.ParamJSON{ParamName: args[0], ParamValue: args[1]}) + internal.Check(err) + if internal.Verbose { + internal.Print(out) + } + } else { + internal.Exit("Invalid argument: tatcli topic allsetparam --help\n") + } + }, +} diff --git a/tatcli/topic/compute_labels.go b/tatcli/topic/compute_labels.go new file mode 100644 index 0000000..b5c35d5 --- /dev/null +++ b/tatcli/topic/compute_labels.go @@ -0,0 +1,23 @@ +package topic + +import ( + "github.com/ovh/tat" + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" +) + +var cmdTopicComputeLabels = &cobra.Command{ + Use: "computelabels", + Short: "Compute Labels on this topic, only for tat admin and administrators on topic : tatcli topic computelabels ", + Run: func(cmd *cobra.Command, args []string) { + if len(args) == 1 { + out, err := internal.Client().TopicComputeLabels(tat.TopicNameJSON{Topic: args[0]}) + internal.Check(err) + if internal.Verbose { + internal.Print(out) + } + } else { + internal.Exit("Invalid argument: tatcli topic computelabels --help\n") + } + }, +} diff --git a/tatcli/topic/compute_tags.go b/tatcli/topic/compute_tags.go new file mode 100644 index 0000000..18ec42d --- /dev/null +++ b/tatcli/topic/compute_tags.go @@ -0,0 +1,23 @@ +package topic + +import ( + "github.com/ovh/tat" + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" +) + +var cmdTopicComputeTags = &cobra.Command{ + Use: "computetags", + Short: "Compute Tags on this topic, only for tat admin and administrators on topic : tatcli topic computetags ", + Run: func(cmd *cobra.Command, args []string) { + if len(args) == 1 { + out, err := internal.Client().TopicComputeTags(tat.TopicNameJSON{Topic: args[0]}) + internal.Check(err) + if internal.Verbose { + internal.Print(out) + } + } else { + internal.Exit("Invalid argument: tatcli topic computetags --help\n") + } + }, +} diff --git a/tatcli/topic/create.go b/tatcli/topic/create.go new file mode 100644 index 0000000..396ae27 --- /dev/null +++ b/tatcli/topic/create.go @@ -0,0 +1,29 @@ +package topic + +import ( + "strings" + + "github.com/ovh/tat" + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" +) + +var cmdTopicCreate = &cobra.Command{ + Use: "create", + Short: "Create a new topic: tatcli create ", + Run: func(cmd *cobra.Command, args []string) { + if len(args) >= 2 { + description := strings.Join(args[1:], " ") + topic, err := internal.Client().TopicCreate(tat.TopicCreateJSON{ + Topic: args[0], + Description: description, + }) + internal.Check(err) + if internal.Verbose { + internal.Print(topic) + } + } else { + internal.Exit("Invalid argument: tatcli topic create --help\n") + } + }, +} diff --git a/tatcli/topic/delete.go b/tatcli/topic/delete.go new file mode 100644 index 0000000..00beaf3 --- /dev/null +++ b/tatcli/topic/delete.go @@ -0,0 +1,21 @@ +package topic + +import ( + "github.com/ovh/tat" + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" +) + +var cmdTopicDelete = &cobra.Command{ + Use: "delete", + Short: "Delete a topic: tatcli delete ", + Run: func(cmd *cobra.Command, args []string) { + if len(args) == 1 { + out, err := internal.Client().TopicDelete(tat.TopicNameJSON{Topic: args[0]}) + internal.Check(err) + internal.Print(out) + } else { + internal.Exit("Invalid argument: tatcli topic delete --help\n") + } + }, +} diff --git a/tatcli/topic/delete_admin_group.go b/tatcli/topic/delete_admin_group.go new file mode 100644 index 0000000..74661d8 --- /dev/null +++ b/tatcli/topic/delete_admin_group.go @@ -0,0 +1,23 @@ +package topic + +import ( + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" +) + +func init() { + cmdTopicDeleteAdminGroup.Flags().BoolVarP(&recursive, "recursive", "r", false, "Apply Delete Rights Admin recursively") +} + +var cmdTopicDeleteAdminGroup = &cobra.Command{ + Use: "deleteAdminGroup", + Short: "Delete Admin Groups from a topic: tatcli topic deleteAdminGroup [--recursive] []...", + Run: func(cmd *cobra.Command, args []string) { + if len(args) >= 2 { + err := internal.Client().TopicDeleteAdminGroups(args[0], args[1:], recursive) + internal.Check(err) + } else { + internal.Exit("Invalid argument: tatcli topic deleteAdminGroup --help\n") + } + }, +} diff --git a/tatcli/topic/delete_admin_user.go b/tatcli/topic/delete_admin_user.go new file mode 100644 index 0000000..6200549 --- /dev/null +++ b/tatcli/topic/delete_admin_user.go @@ -0,0 +1,23 @@ +package topic + +import ( + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" +) + +func init() { + cmdTopicDeleteAdminUser.Flags().BoolVarP(&recursive, "recursive", "r", false, "Apply Delete Rights Admin recursively") +} + +var cmdTopicDeleteAdminUser = &cobra.Command{ + Use: "deleteAdminUser", + Short: "Delete Admin Users from a topic: tatcli topic deleteAdminUser [--recursive] [username2]...", + Run: func(cmd *cobra.Command, args []string) { + if len(args) >= 2 { + err := internal.Client().TopicDeleteAdminGroups(args[0], args[1:], recursive) + internal.Check(err) + } else { + internal.Exit("Invalid argument: tatcli topic deleteAdminUser --help\n") + } + }, +} diff --git a/tatcli/topic/delete_parameter.go b/tatcli/topic/delete_parameter.go new file mode 100644 index 0000000..ddad9e9 --- /dev/null +++ b/tatcli/topic/delete_parameter.go @@ -0,0 +1,23 @@ +package topic + +import ( + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" +) + +func init() { + cmdTopicDeleteParameter.Flags().BoolVarP(&recursive, "recursive", "r", false, "Remove Parameter recursively") +} + +var cmdTopicDeleteParameter = &cobra.Command{ + Use: "deleteParameter", + Short: "Remove Parameter to a topic: tatcli topic deleteParameter [--recursive] []... ", + Run: func(cmd *cobra.Command, args []string) { + if len(args) >= 2 { + err := internal.Client().TopicDeleteParameters(args[0], args[1:], recursive) + internal.Check(err) + } else { + internal.Exit("Invalid argument: tatcli topic deleteParameter --help\n") + } + }, +} diff --git a/tatcli/topic/delete_ro_group.go b/tatcli/topic/delete_ro_group.go new file mode 100644 index 0000000..2969621 --- /dev/null +++ b/tatcli/topic/delete_ro_group.go @@ -0,0 +1,23 @@ +package topic + +import ( + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" +) + +func init() { + cmdTopicDeleteRoGroup.Flags().BoolVarP(&recursive, "recursive", "r", false, "Apply Delete Rights RO recursively") +} + +var cmdTopicDeleteRoGroup = &cobra.Command{ + Use: "deleteRoGroup", + Short: "Delete Read Only Groups from a topic: tatcli topic deleteRoGroup [--recursive] []...", + Run: func(cmd *cobra.Command, args []string) { + if len(args) >= 2 { + err := internal.Client().TopicDeleteRoGroups(args[0], args[1:], recursive) + internal.Check(err) + } else { + internal.Exit("Invalid argument: tatcli topic deleteRoGroup --help\n") + } + }, +} diff --git a/tatcli/topic/delete_ro_user.go b/tatcli/topic/delete_ro_user.go new file mode 100644 index 0000000..4e4c9c0 --- /dev/null +++ b/tatcli/topic/delete_ro_user.go @@ -0,0 +1,23 @@ +package topic + +import ( + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" +) + +func init() { + cmdTopicDeleteRoUser.Flags().BoolVarP(&recursive, "recursive", "r", false, "Apply Delete Rights RO recursively") +} + +var cmdTopicDeleteRoUser = &cobra.Command{ + Use: "deleteRoUser", + Short: "Delete Read Only Users from a topic: tatcli topic deleteRoUser [--recursive] [username2]...", + Run: func(cmd *cobra.Command, args []string) { + if len(args) >= 2 { + err := internal.Client().TopicDeleteRoUsers(args[0], args[1:], recursive) + internal.Check(err) + } else { + internal.Exit("Invalid argument: tatcli topic deleteRoUser --help\n") + } + }, +} diff --git a/tatcli/topic/delete_rw_group.go b/tatcli/topic/delete_rw_group.go new file mode 100644 index 0000000..e394463 --- /dev/null +++ b/tatcli/topic/delete_rw_group.go @@ -0,0 +1,23 @@ +package topic + +import ( + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" +) + +func init() { + cmdTopicDeleteRwGroup.Flags().BoolVarP(&recursive, "recursive", "r", false, "Apply Delete Rights RW recursively") +} + +var cmdTopicDeleteRwGroup = &cobra.Command{ + Use: "deleteRwGroup", + Short: "Delete Read Write Groups from a topic: tatcli topic deleteRwGroup [--recursive] []...", + Run: func(cmd *cobra.Command, args []string) { + if len(args) >= 2 { + err := internal.Client().TopicDeleteRwGroups(args[0], args[1:], recursive) + internal.Check(err) + } else { + internal.Exit("Invalid argument: tatcli topic deleteRwGroup --help\n") + } + }, +} diff --git a/tatcli/topic/delete_rw_user.go b/tatcli/topic/delete_rw_user.go new file mode 100644 index 0000000..2a42ab9 --- /dev/null +++ b/tatcli/topic/delete_rw_user.go @@ -0,0 +1,23 @@ +package topic + +import ( + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" +) + +func init() { + cmdTopicDeleteRwUser.Flags().BoolVarP(&recursive, "recursive", "r", false, "Apply Delete Rights RW recursively") +} + +var cmdTopicDeleteRwUser = &cobra.Command{ + Use: "deleteRwUser", + Short: "Delete Read Write Users from a topic: tatcli topic deleteRwUser [--recursive] [username2]...", + Run: func(cmd *cobra.Command, args []string) { + if len(args) >= 2 { + err := internal.Client().TopicDeleteRwUsers(args[0], args[1:], recursive) + internal.Check(err) + } else { + internal.Exit("Invalid argument: tatcli topic deleteRwUser --help\n") + } + }, +} diff --git a/tatcli/topic/list.go b/tatcli/topic/list.go new file mode 100644 index 0000000..8a1c0c8 --- /dev/null +++ b/tatcli/topic/list.go @@ -0,0 +1,48 @@ +package topic + +import ( + "github.com/ovh/tat" + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" +) + +var ( + criteriaTopic string + criteriaTopicPath string + criteriaIDTopic string + criteriaDescription string + criteriaDateMinCreation string + criteriaDateMaxCreation string + criteriaGetNbMsgUnread string + criteriaGetOnlyFavorites string + criteriaGetForTatAdmin string +) + +var ( + criteria tat.TopicCriteria +) + +func init() { + cmdTopicList.Flags().StringVarP(&criteria.Topic, "topic", "", "", "Search by Topic name, example: /topicA") + cmdTopicList.Flags().StringVarP(&criteria.TopicPath, "topicPath", "", "", "Search by Topic Path, example: /topicA will return /topicA/subA, /topicA/subB") + cmdTopicList.Flags().StringVarP(&criteria.IDTopic, "idTopic", "", "", "Search by id of topic") + cmdTopicList.Flags().StringVarP(&criteria.Description, "description", "", "", "Search by description of topic") + cmdTopicList.Flags().StringVarP(&criteria.DateMinCreation, "dateMinCreation", "", "", "Filter result on dateCreation, timestamp Unix format") + cmdTopicList.Flags().StringVarP(&criteria.DateMaxCreation, "dateMaxCreation", "", "", "Filter result on dateCreation, timestamp Unix Format") + cmdTopicList.Flags().StringVarP(&criteria.GetNbMsgUnread, "getNbMsgUnread", "", "", "If true, add new array to return, topicsMsgUnread with topic:nbUnreadMsgSinceLastPresenceOnTopic") + cmdTopicList.Flags().StringVarP(&criteria.OnlyFavorites, "getOnlyFavorites", "", "", "If true, returns only favorites topics, except /Private/* (all /Private/* are returned)") + cmdTopicList.Flags().StringVarP(&criteria.GetForTatAdmin, "getForTatAdmin", "", "", "(AdminOnly) If true, and requester is a Tat Admin, returns all topics (except /Private/*) without checking user / group access (RO or RW on Topic)") +} + +var cmdTopicList = &cobra.Command{ + Use: "list", + Short: "List all topics: tatcli topic list [] [], tatcli topic list -h for see all criterias", + Aliases: []string{"l"}, + Run: func(cmd *cobra.Command, args []string) { + criteria.Skip, criteria.Limit = internal.GetSkipLimit(args) + c := internal.Client() + out, err := c.TopicList(&criteria) + internal.Check(err) + internal.Print(out) + }, +} diff --git a/tatcli/topic/parameter.go b/tatcli/topic/parameter.go new file mode 100644 index 0000000..29e0dc9 --- /dev/null +++ b/tatcli/topic/parameter.go @@ -0,0 +1,58 @@ +package topic + +import ( + "strconv" + + "github.com/ovh/tat" + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" +) + +func init() { + cmdTopicParameter.Flags().BoolVarP(&recursive, "recursive", "r", false, "Update param topic recursively") +} + +var cmdTopicParameter = &cobra.Command{ + Use: "parameter", + Short: "Update param on one topic: tatcli topic param [--recursive] ", + Aliases: []string{"param"}, + Run: func(cmd *cobra.Command, args []string) { + if len(args) != 11 { + internal.Exit("Invalid parameter to tatcli topic param. See tatcli topic param --help\n") + } + + var err error + + p := tat.TopicParameters{ + Topic: args[0], + } + + p.MaxLength, err = strconv.Atoi(args[1]) + internal.Check(err) + p.MaxReplies, err = strconv.Atoi(args[2]) + internal.Check(err) + p.CanForceDate, err = strconv.ParseBool(args[3]) + internal.Check(err) + p.CanUpdateMsg, err = strconv.ParseBool(args[4]) + internal.Check(err) + p.CanDeleteMsg, err = strconv.ParseBool(args[5]) + internal.Check(err) + p.CanUpdateAllMsg, err = strconv.ParseBool(args[6]) + internal.Check(err) + p.CanDeleteAllMsg, err = strconv.ParseBool(args[7]) + internal.Check(err) + p.AdminCanUpdateAllMsg, err = strconv.ParseBool(args[8]) + internal.Check(err) + p.AdminCanDeleteAllMsg, err = strconv.ParseBool(args[9]) + internal.Check(err) + p.IsAutoComputeTags, err = strconv.ParseBool(args[10]) + internal.Check(err) + p.IsAutoComputeLabels, err = strconv.ParseBool(args[11]) + internal.Check(err) + out, err := internal.Client().TopicParameter(p) + internal.Check(err) + if internal.Verbose { + internal.Print(out) + } + }, +} diff --git a/tatcli/topic/topic.go b/tatcli/topic/topic.go new file mode 100644 index 0000000..58fb702 --- /dev/null +++ b/tatcli/topic/topic.go @@ -0,0 +1,45 @@ +package topic + +import ( + "github.com/spf13/cobra" +) + +var recursive bool + +func init() { + Cmd.AddCommand(cmdTopicList) + Cmd.AddCommand(cmdTopicCreate) + Cmd.AddCommand(cmdTopicDelete) + Cmd.AddCommand(cmdTopicTruncate) + Cmd.AddCommand(cmdTopicAddRoUser) + Cmd.AddCommand(cmdTopicComputeLabels) + Cmd.AddCommand(cmdTopicTruncateLabels) + Cmd.AddCommand(cmdTopicComputeTags) + Cmd.AddCommand(cmdTopicTruncateTags) + Cmd.AddCommand(cmdTopicAllComputeLabels) + Cmd.AddCommand(cmdTopicAllComputeTags) + Cmd.AddCommand(cmdTopicAllComputeReplies) + Cmd.AddCommand(cmdTopicAllSetParam) + Cmd.AddCommand(cmdTopicAddRwUser) + Cmd.AddCommand(cmdTopicAddAdminUser) + Cmd.AddCommand(cmdTopicDeleteRoUser) + Cmd.AddCommand(cmdTopicDeleteRwUser) + Cmd.AddCommand(cmdTopicDeleteAdminUser) + Cmd.AddCommand(cmdTopicAddRoGroup) + Cmd.AddCommand(cmdTopicAddRwGroup) + Cmd.AddCommand(cmdTopicAddAdminGroup) + Cmd.AddCommand(cmdTopicDeleteRoGroup) + Cmd.AddCommand(cmdTopicDeleteRwGroup) + Cmd.AddCommand(cmdTopicDeleteAdminGroup) + Cmd.AddCommand(cmdTopicAddParameter) + Cmd.AddCommand(cmdTopicDeleteParameter) + Cmd.AddCommand(cmdTopicParameter) +} + +// Cmd topic +var Cmd = &cobra.Command{ + Use: "topic", + Short: "Topic commands: tatcli topic --help", + Long: "Topic commands: tatcli topic [command]", + Aliases: []string{"t"}, +} diff --git a/tatcli/topic/truncate.go b/tatcli/topic/truncate.go new file mode 100644 index 0000000..5c2f1d8 --- /dev/null +++ b/tatcli/topic/truncate.go @@ -0,0 +1,57 @@ +package topic + +import ( + "fmt" + + "github.com/ovh/tat" + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" +) + +var force bool + +func init() { + cmdTopicTruncate.Flags().BoolVarP(&force, "force", "", false, "--force : truncate without asking confirmation") +} + +var cmdTopicTruncate = &cobra.Command{ + Use: "truncate", + Short: "Remove all messages in a topic, only for tat admin and administrators on topic : tatcli topic truncate [--force]", + Run: func(cmd *cobra.Command, args []string) { + if len(args) == 1 { + topicTruncate(args[0]) + } else { + internal.Exit("Invalid argument: tatcli topic truncate --help\n") + } + }, +} + +func topicTruncate(topic string) { + j := tat.TopicNameJSON{Topic: topic} + if force { + out, err := internal.Client().TopicTruncate(j) + internal.Check(err) + if internal.Verbose { + internal.Print(out) + } + } else { + fmt.Print("Are you really sure ? You will delete all messages even if a user has a message in his tasks. Please enter again topic name to confirm: ") + var confirmTopic string + fmt.Scanln(&confirmTopic) + + if confirmTopic == topic { + fmt.Printf("Please enter 'yes' to confirm removing all messages from %s: ", topic) + var confirmYes string + fmt.Scanln(&confirmYes) + if confirmYes == "yes" { + out, err := internal.Client().TopicTruncate(j) + internal.Check(err) + internal.Print(out) + return + } + } else { + fmt.Printf("Error. You enter %s instead of %s\n", confirmTopic, topic) + } + fmt.Println("Nothing done") + } +} diff --git a/tatcli/topic/truncate_labels.go b/tatcli/topic/truncate_labels.go new file mode 100644 index 0000000..3d55376 --- /dev/null +++ b/tatcli/topic/truncate_labels.go @@ -0,0 +1,23 @@ +package topic + +import ( + "github.com/ovh/tat" + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" +) + +var cmdTopicTruncateLabels = &cobra.Command{ + Use: "truncatelabels", + Short: "Truncate Labels on this topic, only for tat admin and administrators on topic : tatcli topic truncatelabels ", + Run: func(cmd *cobra.Command, args []string) { + if len(args) == 1 { + out, err := internal.Client().TopicTruncateLabels(tat.TopicNameJSON{Topic: args[0]}) + internal.Check(err) + if internal.Verbose { + internal.Print(out) + } + } else { + internal.Exit("Invalid argument: tatcli topic truncatelabels --help\n") + } + }, +} diff --git a/tatcli/topic/truncate_tags.go b/tatcli/topic/truncate_tags.go new file mode 100644 index 0000000..df8a62c --- /dev/null +++ b/tatcli/topic/truncate_tags.go @@ -0,0 +1,23 @@ +package topic + +import ( + "github.com/ovh/tat" + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" +) + +var cmdTopicTruncateTags = &cobra.Command{ + Use: "truncatetags", + Short: "Truncate Tags on this topic, only for tat admin and administrators on topic : tatcli topic truncatetags ", + Run: func(cmd *cobra.Command, args []string) { + if len(args) == 1 { + out, err := internal.Client().TopicTruncateTags(tat.TopicNameJSON{Topic: args[0]}) + internal.Check(err) + if internal.Verbose { + internal.Print(out) + } + } else { + internal.Exit("Invalid argument: tatcli topic truncatetags --help\n") + } + }, +} diff --git a/tatcli/ui/cmd.go b/tatcli/ui/cmd.go new file mode 100644 index 0000000..0e64251 --- /dev/null +++ b/tatcli/ui/cmd.go @@ -0,0 +1,33 @@ +package ui + +import ( + "github.com/gizak/termui" + "github.com/spf13/cobra" +) + +// Cmd dashboard +var Cmd = &cobra.Command{ + Use: "ui", + Short: "Interactive mode: tatcli ui [] [,,...]", + Long: `Interactive mode: tatcli ui [] [,,...] +Example: + + tatcli ui /YourTopic/SubTopic /run AA,BB /hide-usernames /hide-top + tatcli ui /YourTopic/SubTopic /split label:open label:doing label:done /mode run /save + tatcli ui /YourTopic/SubTopic /run AA,BB /hide-usernames /hide-bottom /save + + `, + Aliases: []string{"d", "dashboard"}, + Run: func(cmd *cobra.Command, args []string) { + runUI(args) + }, +} + +func runUI(args []string) { + ui := &tatui{} + ui.init(args) + ui.draw(0) + + defer termui.Close() + termui.Loop() +} diff --git a/tatcli/ui/config.go b/tatcli/ui/config.go new file mode 100644 index 0000000..afb4852 --- /dev/null +++ b/tatcli/ui/config.go @@ -0,0 +1,144 @@ +package ui + +import ( + "encoding/json" + "io/ioutil" + "os" + "path" + "strings" + + "github.com/asaskevich/govalidator" + "github.com/ovh/tat" + "github.com/ovh/tat/tatcli/config" + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/viper" +) + +func (ui *tatui) loadConfig() { + internal.ReadConfig() + filters := viper.GetStringSlice("filters") + + // no range to keep order + for index := 0; index < len(filters); index++ { + filter := filters[index] + tuples := strings.Split(filter, " ") + if len(tuples) <= 2 { + continue + } + topic := tuples[1] + if _, ok := ui.currentFilterMessages[topic]; !ok { + ui.currentFilterMessages[topic] = make(map[int]*tat.MessageCriteria) + ui.currentFilterMessagesText[topic] = make(map[int]string) + } + c, criteriaText := ui.prepareFilterMessages(strings.Join(tuples[2:], " "), tuples[0], topic) + ui.currentFilterMessages[topic][len(ui.currentFilterMessages[topic])] = c + ui.currentFilterMessagesText[topic][len(ui.currentFilterMessagesText[topic])] = criteriaText + } + + commands := viper.GetStringSlice("commands") + // no range to keep order + for index := 0; index < len(commands); index++ { + commandsOnTopic := commands[index] + tuples := strings.Split(strings.TrimSpace(commandsOnTopic), " ") + if len(tuples) <= 1 { + continue + } + topic := tuples[0] + ui.uiTopicCommands[topic] = commandsOnTopic[len(topic):] + } + + var conf config.TemplateJSONType + err := viper.Unmarshal(&conf) + if err != nil { + internal.Exit("unable to decode confif file, err: %v", err) + } + + ui.hooks = conf.Hooks +} + +func (ui *tatui) setTatWebUIURL(str string) { + str = strings.Replace(str, "/set-tatwebui-url ", "", 1) + if str == "" { + return + } + validURL := govalidator.IsURL(str) + if !validURL { + ui.msg.Text = "You entered an invalid URL" + ui.render() + return + } + viper.Set("tatwebui-url", str) + ui.saveConfig() +} + +func (ui *tatui) saveConfig() { + var templateJSON config.TemplateJSONType + + if viper.GetString("url") == "" || + viper.GetString("username") == "" || + viper.GetString("password") == "" { + ui.msg.Text = " Conf not saved: url, username or password empty" + return + } + + if viper.GetString("username") != "" { + templateJSON.Username = viper.GetString("username") + } + if viper.GetString("password") != "" { + templateJSON.Password = viper.GetString("password") + } + if viper.GetString("url") != "" { + templateJSON.URL = viper.GetString("url") + } + if viper.GetString("tatwebui-url") != "" { + templateJSON.TatwebuiURL = viper.GetString("tatwebui-url") + } + if viper.GetString("hook-run-action") != "" { + templateJSON.PostHookRunAction = viper.GetString("post-hook-run-action") + } + + templateJSON.Hooks = ui.hooks + + var filters []string + for _, criteriasForTopic := range ui.currentFilterMessagesText { + for index := 0; index < len(criteriasForTopic); index++ { + // not this, for keeping order for _, criteria := range criteriasForTopic + criteria := criteriasForTopic[index] + toAdd := strings.TrimSpace(criteria) + if toAdd != "" { + filters = append(filters, toAdd) + } + } + } + templateJSON.Filters = filters + + var commands []string + for topic, topicCommands := range ui.uiTopicCommands { + if strings.TrimSpace(topicCommands) != "" { + commands = append(commands, topic+topicCommands) + } + } + templateJSON.Commands = commands + + jsonStr, err := json.MarshalIndent(templateJSON, "", " ") + if err != nil { + ui.msg.Text = " Error while preparing config.json" + return + } + jsonStr = append(jsonStr, '\n') + filename := internal.ConfigFile + + dir := path.Dir(filename) + if _, e := os.Stat(dir); os.IsNotExist(e) { + err2 := os.Mkdir(dir, 0740) + ui.msg.Text = " Error while saving config.json " + err2.Error() + return + } + + if err := ioutil.WriteFile(filename, jsonStr, 0600); err != nil { + ui.msg.Text = " Error while saving config.json " + err.Error() + return + } + + ui.msg.Text = "Config file is saved" +} diff --git a/tatcli/ui/events.go b/tatcli/ui/events.go new file mode 100644 index 0000000..fe326c9 --- /dev/null +++ b/tatcli/ui/events.go @@ -0,0 +1,447 @@ +package ui + +import ( + "fmt" + "strings" + + "github.com/gizak/termui" + "github.com/ovh/tat/tatcli/internal" + "github.com/skratchdot/open-golang/open" + "github.com/spf13/viper" +) + +func (ui *tatui) initHandles() { + // Setup handlers + termui.Handle("/timer/1s", func(e termui.Event) { + t := e.Data.(termui.EvtTimer) + ui.draw(int(t.Count)) + }) + + termui.Handle("/sys/kbd/C-q", func(termui.Event) { + termui.StopLoop() + }) + + // Show Home -> C-h, but send event + termui.Handle("/sys/kbd/", func(e termui.Event) { + ui.showHome() + }) + + // C-c is same as /clear + termui.Handle("/sys/kbd/C-c", func(e termui.Event) { + ui.clearUI() + }) + + // All topics + termui.Handle("/sys/kbd/C-b", func(e termui.Event) { + if ui.current == uiMessage { + ui.showMessages() + } + }) + + // All topics + termui.Handle("/sys/kbd/C-a", func(e termui.Event) { + ui.current = uiTopics + ui.onlyFavorites = "false" + ui.onlyUnread = false + ui.showTopics() + }) + + // Unread Topics + termui.Handle("/sys/kbd/C-r", func(e termui.Event) { + ui.showUnreadTopics() + }) + + // toggle usernames + termui.Handle("/sys/kbd/C-u", func(e termui.Event) { + ui.toggleUsernames(false) + }) + + // Favorites Topics + termui.Handle("/sys/kbd/C-f", func(e termui.Event) { + ui.showFavoritesTopics() + }) + + termui.Handle("/sys/kbd/", func(e termui.Event) { + ui.move("up") + }) + + termui.Handle("/sys/kbd/", func(e termui.Event) { + ui.move("down") + }) + + termui.Handle("/sys/kbd/", func(e termui.Event) { + switch ui.selectedPane { + case uiTopics: + ui.enterTopic() + return + case uiMessages: + ui.enterMessage() + return + case uiActionBox: + ui.processMsg() + ui.render() + } + }) + + termui.Handle("/sys/kbd/", func(e termui.Event) { + if ui.isOnActionBox() { + ui.send.Text += " " + } + ui.render() + }) + + termui.Handle("/sys/kbd/", func(e termui.Event) { + if ui.isOnActionBox() && len(ui.send.Text) > 0 && !strings.HasSuffix(ui.send.Text, " ") { + ui.autocomplete() + } else { + ui.switchBox() + } + }) + + termui.Handle("/sys/kbd/C-8", func(e termui.Event) { + if !ui.isOnActionBox() { + return + } + if len(ui.send.Text) > 0 { + ui.send.Text = ui.send.Text[:len(ui.send.Text)-1] + ui.render() + } + }) + + termui.Handle("/sys/kbd/C-k", func(e termui.Event) { + if ui.currentModeOnTopic[ui.currentTopic.Topic] == "/run" { + ui.runActionOnMessage(true) + } else if ui.currentModeOnTopic[ui.currentTopic.Topic] == "/monitoring" { + ui.monitoringActionOnMessage() + } + }) + + termui.Handle("/sys/kbd/C-j", func(e termui.Event) { + if ui.currentModeOnTopic[ui.currentTopic.Topic] == "/run" { + ui.runActionOnMessage(false) + } else if ui.currentModeOnTopic[ui.currentTopic.Topic] == "/monitoring" { + ui.monitoringActionOnMessage() + } + }) + + termui.Handle("/sys/kbd/C-p", func(e termui.Event) { + if _, ok := ui.uilists[uiMessages][ui.selectedPaneMessages]; ok { + ui.openLinksInBrowser() + } + }) + + termui.Handle("/sys/kbd/C-t", func(e termui.Event) { + ui.toggleTopMenu(false) + }) + + termui.Handle("/sys/kbd/C-y", func(e termui.Event) { + ui.toggleActionBox(false) + }) + + termui.Handle("/sys/kbd/C-o", func(e termui.Event) { + if _, ok := ui.uilists[uiMessages][ui.selectedPaneMessages]; ok { + ui.openInTatwebui() + } + }) + + termui.Handle("/sys/kbd", func(e termui.Event) { + if !ui.isOnActionBox() { + ui.switchToActionBox() + } + ui.send.BorderFg = termui.ColorRed + if _, ok := ui.uilists[uiActionBox][0]; ok { + ui.uilists[uiActionBox][0].list.BorderFg = termui.ColorWhite + } + char := e.Data.(termui.EvtKbd).KeyStr + ui.send.Text += char + ui.render() + }) + + for _, h := range ui.hooks { + if h.Shortcut == "" { + continue + } + if _, ok := termui.DefaultEvtStream.Handlers["/sys/kbd/"+h.Shortcut]; ok { + internal.Exit("Shortcut %s is already used in tatcli", h.Shortcut) + } + termui.Handle("/sys/kbd/"+h.Shortcut, func(e termui.Event) { + ui.RunExec(nil, e.Path, "") + }) + } + +} + +func (ui *tatui) moveHistory(direction string) { + if direction == "up" { + ui.currentPosHistory-- + if ui.currentPosHistory < 0 { + ui.currentPosHistory = 0 + } + } else { // down + ui.currentPosHistory++ + if ui.currentPosHistory >= len(ui.history) { + ui.currentPosHistory = len(ui.history) - 1 + ui.send.Text = "" + ui.render() + return + } + } + if ui.currentPosHistory >= 0 && ui.currentPosHistory < len(ui.history) { + ui.send.Text = ui.history[ui.currentPosHistory] + } + ui.render() +} + +func (ui *tatui) move(direction string) { + if ui.selectedPane == uiActionBox { + ui.moveHistory(direction) + return + } + if ui.selectedPane != uiMessages && + ui.selectedPane != uiMessage && + ui.selectedPane != uiTopics { + return + } + + //ui.selectedPane = ui.current + ui.colorizedPanes() + if direction == "up" { + if ui.selectedPane == uiMessages { + ui.moveUP(ui.uilists[ui.selectedPane][ui.selectedPaneMessages]) + } else { + ui.moveUP(ui.uilists[ui.selectedPane][0]) + } + } else { + if ui.selectedPane == uiMessages { + ui.moveDown(ui.uilists[ui.selectedPane][ui.selectedPaneMessages]) + } else { + ui.moveDown(ui.uilists[ui.selectedPane][0]) + } + } +} + +func (ui *tatui) moveUP(uil *uilist) { + p := uil.position + uil.position-- + if uil.position < 0 { + uil.page-- + if uil.page < 0 { + uil.page = 0 + uil.position = 0 + } else { + uil.update() + uil.position = len(uil.list.Items) - 1 + } + } + if p != uil.position { + ui.removeMarker(uil, ui.selectedPaneMessages, p) + ui.addMarker(uil, ui.selectedPaneMessages) + } +} + +func (ui *tatui) moveDown(uil *uilist) { + p := uil.position + uil.position++ + nbPerPage := 1 + if uil.uiType == uiMessages { + nbPerPage = (ui.getNbPerPage() / len(ui.currentFilterMessages[ui.currentTopic.Topic])) - 1 + } else { + nbPerPage = ui.getNbPerPage() + } + + if uil.position >= len(uil.list.Items) && nbPerPage == len(uil.list.Items) { + uil.page++ + uil.update() + uil.position = 0 + } else if nbPerPage > len(uil.list.Items) && uil.position >= len(uil.list.Items) { + uil.position-- + } + if p != uil.position { + ui.removeMarker(uil, ui.selectedPaneMessages, p) + ui.addMarker(uil, ui.selectedPaneMessages) + } +} + +func (ui *tatui) addMarker(uil *uilist, selectedPane int) { + if uil == nil || uil.list.Items == nil || uil.position < 0 || uil.position >= len(uil.list.Items) { + return + } + if uil.uiType == uiMessages && ui.currentListMessages != nil { + _, ok := ui.currentListMessages[selectedPane] + if ok && len(ui.currentListMessages[selectedPane]) > uil.position { + uil.list.Items[uil.position] = fmt.Sprintf("[%s](bg-green)", ui.formatMessage(ui.currentListMessages[selectedPane][uil.position], false)) + } + } else if uil.uiType == uiTopics && ui.currentListTopic != nil { + if len(ui.currentListTopic) > uil.position { + topic, _ := ui.formatTopic(ui.currentListTopic[uil.position], false) + uil.list.Items[uil.position] = fmt.Sprintf("[%s](bg-green)", topic) + } + } else { + uil.list.Items[uil.position] = fmt.Sprintf("[➨](fg-green) %s", uil.list.Items[uil.position]) + } + ui.render() +} + +func (ui *tatui) removeMarker(uil *uilist, selectedPane, pos int) { + if pos < 0 || pos >= len(uil.list.Items) { + return + } + if uil.uiType == uiMessages && ui.currentListMessages != nil { + uil.list.Items[pos] = ui.formatMessage(ui.currentListMessages[selectedPane][pos], true) + } else if uil.uiType == uiTopics && ui.currentListTopic != nil { + topic, _ := ui.formatTopic(ui.currentListTopic[pos], true) + uil.list.Items[pos] = topic + } else { + uil.list.Items[pos] = strings.Replace(uil.list.Items[pos], "[➨](fg-green) ", "", 1) + } + ui.render() +} + +func (ui *tatui) switchToActionBox() { + ui.selectedPane = uiActionBox + ui.colorizedPanes() +} + +func (ui *tatui) switchBox() { + switch ui.current { + case uiHome, uiResult: + ui.switchBoxFromHome() + case uiTopics: + ui.switchBoxFromTopics() + case uiMessages: + ui.switchBoxFromMessages() + case uiMessage: + ui.switchBoxFromMessage() + } + ui.colorizedPanes() + termui.Clear() + ui.render() +} + +func (ui *tatui) switchBoxFromHome() { + ui.selectedPane = uiActionBox + ui.send.BorderFg = termui.ColorRed +} + +func (ui *tatui) switchBoxFromTopics() { + switch ui.selectedPane { + case uiActionBox: + ui.selectedPane = uiTopics + case uiTopics: + if _, ok := ui.uilists[uiMessage][0]; ok { + ui.selectedPane = uiMessage + } else if _, ok := ui.uilists[uiMessages][0]; ok { + ui.selectedPane = uiMessages + } else { + ui.selectedPane = uiActionBox + } + case uiMessages, uiMessage: + ui.selectedPane = uiActionBox + } +} + +func (ui *tatui) switchBoxFromMessages() { + switch ui.selectedPane { + case uiActionBox: + if len(ui.currentFilterMessages[ui.currentTopic.Topic]) == 1 { + ui.selectedPane = uiTopics + } else { + ui.selectedPane = uiMessages + ui.selectedPaneMessages = 0 + ui.addMarker(ui.uilists[uiMessages][ui.selectedPaneMessages], ui.selectedPaneMessages) + } + case uiTopics: + ui.selectedPane = uiMessages + ui.selectedPaneMessages = 0 + case uiMessages: + if len(ui.currentFilterMessages[ui.currentTopic.Topic]) == 1 { + ui.selectedPane = uiActionBox + } else { + ui.removeMarker(ui.uilists[uiMessages][ui.selectedPaneMessages], ui.selectedPaneMessages, ui.uilists[uiMessages][ui.selectedPaneMessages].position) + ui.selectedPaneMessages++ + if ui.selectedPaneMessages >= len(ui.currentFilterMessages[ui.currentTopic.Topic]) { + ui.selectedPaneMessages = 0 + ui.selectedPane = uiActionBox + } + if ui.selectedPane == uiMessages { + ui.addMarker(ui.uilists[uiMessages][ui.selectedPaneMessages], ui.selectedPaneMessages) + } + } + } +} + +func (ui *tatui) switchBoxFromMessage() { + switch ui.selectedPane { + case uiActionBox: + ui.selectedPane = uiTopics + case uiTopics: + ui.selectedPane = uiMessage + case uiMessage: + ui.selectedPane = uiActionBox + } +} + +func (ui *tatui) openLinksInBrowser() { + msg := ui.currentListMessages[ui.selectedPaneMessages][ui.uilists[uiMessages][ui.selectedPaneMessages].position] + for _, url := range msg.Urls { + open.Run(url) + } +} + +func (ui *tatui) toggleUsernames(forceHide bool) { + ui.toggleActionOnTopic(" /hide-usernames", forceHide) + ui.updateMessages() +} + +func (ui *tatui) openInTatwebui() { + msg := ui.currentListMessages[ui.selectedPaneMessages][ui.uilists[uiMessages][ui.selectedPaneMessages].position] + base := strings.TrimSpace(viper.GetString("tatwebui-url")) + + if base == "" { + ui.msg.Text = "You need to set TatWebui URL in your config file, see /set-tatwebui-url" + ui.render() + return + } + + view := "standardview" + + // search view setted on topic parameters + for _, p := range ui.currentTopic.Parameters { + if p.Key == "tatwebui.view.restricted" && p.Value != "" { + view = strings.TrimSpace(strings.Replace(p.Value, "-list", "", 1)) + break + } else if p.Key == "tatwebui.view.default" && p.Value != "" { + view = strings.TrimSpace(strings.Replace(p.Value, "-list", "", 1)) + } + } + if !strings.HasSuffix(base, "/") { + view = "/" + view + } + url := fmt.Sprintf("%s%s/list%s?idMessage=%s", base, view, ui.currentTopic.Topic, msg.ID) + open.Run(url) +} + +func (ui *tatui) colorizedPanes() { + if _, ok := ui.uilists[uiTopics]; ok { + ui.uilists[uiTopics][0].list.BorderFg = termui.ColorWhite + } + if _, ok := ui.uilists[uiMessages]; ok { + for k := range ui.currentFilterMessages[ui.currentTopic.Topic] { + ui.uilists[uiMessages][k].list.BorderFg = termui.ColorWhite + } + } + if _, ok := ui.uilists[uiMessage]; ok { + ui.uilists[uiMessage][0].list.BorderFg = termui.ColorWhite + } + + ui.send.BorderFg = termui.ColorWhite + + switch ui.selectedPane { + case uiActionBox: + ui.send.BorderFg = termui.ColorRed + case uiTopics, uiMessage: + ui.uilists[ui.selectedPane][0].list.BorderFg = termui.ColorRed + case uiMessages: + ui.uilists[ui.selectedPane][ui.selectedPaneMessages].list.BorderFg = termui.ColorRed + } +} diff --git a/tatcli/ui/home.go b/tatcli/ui/home.go new file mode 100644 index 0000000..574e3d0 --- /dev/null +++ b/tatcli/ui/home.go @@ -0,0 +1,141 @@ +package ui + +import ( + "github.com/gizak/termui" + "github.com/spf13/viper" + + "github.com/ovh/tat" + "github.com/ovh/tat/tatcli/internal" +) + +func (ui *tatui) showHome() { + ui.current = uiHome + ui.selectedPane = uiActionBox + termui.Body.Rows = nil + + ui.prepareTopMenu() + + termui.Body.AddRows( + termui.NewRow( + termui.NewCol(5, 0, ui.homeLeft), + termui.NewCol(7, 0, ui.homeRight), + ), + ) + ui.prepareSendRow() + termui.Clear() + ui.colorizedPanes() + ui.render() +} + +func (ui *tatui) initHome() { + ui.initHomeLeft() + ui.initHomeRight() +} + +func (ui *tatui) initHomeLeft() { + + textURL := viper.GetString("url") + if textURL == "" { + textURL = "[Invalid URL, please check your config file](fg-red)" + } + + p := termui.NewPar(` TEXT AND TAGS + ---------------------------------------------- + ---------------------------------------------- + ||| ||| + ||| ||| + ||| ||| ||| + ||| ||| ||| + ||| ||| + ||| ||| ||| + ||| ||| ||| + ||| ||| + ||| ||| + + Tatcli Version: ` + tat.Version + ` + https://github.com/ovh/tat/tatcli + TAT Engine: https://github.com/ovh/tat + Current Tat Engine: ` + textURL + ` + Current config file: ` + internal.ConfigFile + ` + Shortcuts: + - Ctrl + a to view all topics. Cmd /topics in send box + - Ctrl + b to go back to messsages list, after selected a message + - Ctrl + c clears filters and UI on current messages list + - Ctrl + f to view favorites topics. Cmd /favorites + - Ctrl + h to go back home. Cmd /home or /help + - Ctrl + t hide or show top menu. Cmd /toggle-top + - Ctrl + y hide or show actionbox menu. Cmd /toggle-bottom + - Ctrl + o open current message on tatwebui with a browser. Cmd /open + Use option tatwebui-url in config file. See /set-tatwebui-url + - Ctrl + p open links in current message with a browser. Cmd /open-links + - Ctrl + j / Ctrl + k (for reverse action): + if mode run is enabled, set a msg from open to doing, + from doing to done from done to open. + if mode monitoring is enabled, set a msg from UP to AL, + from AL to UP. + - Ctrl + q to quit. Cmd /quit + - Ctrl + r to view unread topics. Cmd /unread + - Ctrl + u display/hide usernames in messages list. Cmd /toggle-usernames + - UP / Down to move into topics & messages list + - UP / Down to navigate through history of action box + - to go to next section on screen`) + + p.Height = termui.TermHeight() - uiHeightTop - uiHeightSend + p.TextFgColor = termui.ColorWhite + p.BorderTop = true + p.BorderLeft = false + p.BorderBottom = false + ui.homeLeft = p +} + +func (ui *tatui) initHomeRight() { + p := termui.NewPar(`Action Box + + Keywords: + - /help display this page + - /me show information about you + - /version to show tatcli and engine version + + On messages list: + - /label eeeeee yourLabel to add a label on selected message + - /unlabel yourLabel to remove label "yourLabel" on selected message + - /voteup, /votedown, /unvoteup, /unvotedown to vote up or down, or remove vote + - /task, /untask to add or remove selected message as a personal task + - /like, /unlike to add or remove like on selected message + - /filter label:labelA,labelB andtag:tag,tagb + - /mode (run|monitoring): enable Ctrl + l shortcut, see on left side for help + - /codereview splits screen into fours panes: + label:OPENED label:APPROVED label:MERGED label:DECLINED + - /monitoring splits screen into three panes: label:UP, label:AL, notlabel:AL,UP + This is the same as two commands: + - /split label:UP label:AL notlabel:AL,UP + - /mode monitoring + - /run splits screen into three panes: label:open, label:doing, label:done + /run AA,BB is the same as two commands: + - /split tag:AA,BB;label:open tag:AA,BB;label:doing tag:AA,BB;label:done + - /mode run + - /set-tatwebui-url sets tatwebui-url in tatcli config file. This + url is used by Ctrl + o shortcut to open message with a tatwebui instance. + - /split splits screen with one section per criteria delimited by space, ex: + /split label:labelA label:labelB label:labelC + /split label:labelA,labelB andtag:tag,tagb + /split tag:myTag;label:labelA,labelB andtag:tag,tagb;label:labelC + - /save saves current filters in tatcli config file + - /toggle-usernames displays or hides username in messages list + + For /split and /filter, see all parameters on https://github.com/ovh/tat#parameters + + On topics list, ex: + - /filter topic:/Private/firstname.lastname + see all parameters on https://github.com/ovh/tat#parameters-4 + +`) + + p.Height = termui.TermHeight() - uiHeightTop - uiHeightSend + p.TextFgColor = termui.ColorWhite + p.BorderTop = true + p.BorderLeft = false + p.BorderRight = false + p.BorderBottom = false + ui.homeRight = p +} diff --git a/tatcli/ui/message.go b/tatcli/ui/message.go new file mode 100644 index 0000000..ee86cc0 --- /dev/null +++ b/tatcli/ui/message.go @@ -0,0 +1,116 @@ +package ui + +import ( + "fmt" + "time" + + "github.com/gizak/termui" + "github.com/ovh/tat" + "github.com/ovh/tat/tatcli/internal" +) + +func (ui *tatui) showMessage() { + ui.current = uiMessage + ui.selectedPane = uiMessage + ui.send.BorderLabel = " ✎ Action or New Reply " + termui.Body.Rows = nil + + if ui.uilists[uiMessages][ui.selectedPaneMessages].list == nil || ui.uilists[uiMessages][ui.selectedPaneMessages].position < 0 { + return + } + + ui.uilists[uiMessage] = make(map[int]*uilist) + + ui.initMessage() + + go func() { + for { + if ui.current != uiMessage { + break + } + mutex.Lock() + ui.updateMessage() + mutex.Unlock() + time.Sleep(5 * time.Second) + } + }() + ui.addMarker(ui.uilists[uiMessage][0], 0) + + ui.prepareTopMenu() + termui.Body.AddRows( + termui.NewRow( + termui.NewCol(3, 0, ui.uilists[uiTopics][0].list), + termui.NewCol(9, 0, ui.uilists[uiMessage][0].list), + ), + ) + ui.prepareSendRow() + ui.colorizedPanes() + termui.Clear() + ui.render() +} + +func (ui *tatui) initMessage() { + strs := []string{"[Loading...](fg-black,bg-white)"} + + ls := termui.NewList() + ls.BorderTop, ls.BorderLeft, ls.BorderRight, ls.BorderBottom = true, false, false, false + ls.Items = strs + ls.ItemFgColor = termui.ColorWhite + ls.BorderLabel = "Message" + ls.Overflow = "wrap" + ls.Width = 25 + ls.Y = 0 + ls.Height = termui.TermHeight() - uiHeightTop - uiHeightSend + _, ok := ui.uilists[uiMessages][ui.selectedPaneMessages] + if ok && ui.uilists[uiMessages][ui.selectedPaneMessages].position >= 0 && ui.uilists[uiMessages][ui.selectedPaneMessages].position < len(ui.currentListMessages[ui.selectedPaneMessages]) { + ui.currentMessage = ui.currentListMessages[ui.selectedPaneMessages][ui.uilists[uiMessages][ui.selectedPaneMessages].position] + ui.uilists[uiMessage][0] = &uilist{uiType: uiMessage, list: ls, position: 0, page: 0, update: ui.updateMessage} + } +} + +func (ui *tatui) updateMessage() { + start := time.Now().UnixNano() + + c := &tat.MessageCriteria{ + IDMessage: ui.currentMessage.ID, + Topic: ui.currentTopic.Topic, + TreeView: "onetree", + } + messagesJSON, err := internal.Client().MessageList(ui.currentTopic.Topic, c) + if err != nil { + ui.msg.Text = err.Error() + ui.render() + return + } + + thread := []string{} + for _, msg := range messagesJSON.Messages { + thread = ui.addMessage(msg, 0) + } + + ui.uilists[uiMessage][0].list.Items = thread + ui.uilists[uiMessage][0].list.BorderLabel = " View Message, Ctrl+b to return back " + delta := int64((time.Now().UnixNano() - start) / 1000000) + ui.lastRefresh.Text = fmt.Sprintf("%s (%dms)", time.Now().Format(time.Stamp), delta) + ui.msg.Text = "" +} + +func (ui *tatui) addMessage(msg tat.Message, deep int) []string { + text := "" + for n := 0; n < deep; n++ { + text += " " + } + if deep > 0 { + text += " ➥ " + } + + text += ui.formatMessage(msg, true) + + thread := []string{} + thread = append(thread, text) + deep++ + for _, replies := range msg.Replies { + thread = append(thread, ui.addMessage(replies, deep)...) + } + return thread +} diff --git a/tatcli/ui/messages.go b/tatcli/ui/messages.go new file mode 100644 index 0000000..6b3dffb --- /dev/null +++ b/tatcli/ui/messages.go @@ -0,0 +1,585 @@ +package ui + +import ( + "encoding/json" + "fmt" + "os/exec" + "strconv" + "strings" + "time" + + "github.com/gizak/termui" + "github.com/ovh/tat" + "github.com/ovh/tat/tatcli/config" + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/viper" +) + +func (ui *tatui) showMessages() { + ui.current = uiMessages + ui.selectedPane = uiMessages + ui.send.BorderLabel = " ✎ Action or New Message " + termui.Body.Rows = nil + + ui.selectedPaneMessages = 0 + + if len(ui.currentListMessages) == 0 { + ui.currentListMessages[0] = nil + } + + if _, ok := ui.uilists[uiTopics]; !ok || len(ui.uilists[uiTopics]) == 0 { + ui.msg.Text = "Please select a topic before doing this action" + ui.showHome() + return + } + + if _, ok := ui.currentFilterMessages[ui.currentTopic.Topic]; !ok { + ui.clearFilterOnCurrentTopic() + } + + ui.initMessages() + + go func() { + for { + if ui.current != uiMessages { + break + } + mutex.Lock() + ui.updateMessages() + ui.firstCallMessages = true + mutex.Unlock() + time.Sleep(5 * time.Second) + } + }() + + ui.uilists[uiTopics][0].list.BorderRight = true + + ui.prepareTopMenu() + + if len(ui.currentFilterMessages[ui.currentTopic.Topic]) > 1 { + // preserve order + for k := 0; k < len(ui.currentFilterMessages[ui.currentTopic.Topic]); k++ { + termui.Body.AddRows(termui.NewRow(termui.NewCol(12, 0, ui.uilists[uiMessages][k].list))) + } + } else { + termui.Body.AddRows( + termui.NewRow( + termui.NewCol(3, 0, ui.uilists[uiTopics][0].list), + termui.NewCol(9, 0, ui.uilists[uiMessages][0].list), + ), + ) + } + + ui.prepareSendRow() + ui.colorizedPanes() + termui.Clear() + ui.render() +} + +func (ui *tatui) initMessages() { + for k := range ui.currentFilterMessages[ui.currentTopic.Topic] { + strs := []string{"[Loading...](fg-black,bg-white)"} + ls := termui.NewList() + ls.BorderTop, ls.BorderLeft, ls.BorderRight, ls.BorderBottom = true, false, false, false + ls.Items = strs + ls.ItemFgColor = termui.ColorWhite + ls.BorderLabel = "Messages" + ls.Width = 25 + ls.Y = 0 + ls.Height = (termui.TermHeight() - uiHeightTop - uiHeightSend) / len(ui.currentFilterMessages[ui.currentTopic.Topic]) + + if _, ok := ui.uilists[uiMessages]; !ok { + ui.uilists[uiMessages] = make(map[int]*uilist) + } + ui.uilists[uiMessages][k] = &uilist{uiType: uiMessages, list: ls, position: 0, page: 0, update: ui.updateMessages} + } + ui.applyLabelOnMsgPanes() + ui.render() +} + +func (ui *tatui) enterMessage() { + ui.showMessage() + ui.render() +} + +func (ui *tatui) updateMessages() { + start := time.Now().UnixNano() + ui.msg.Text = "" + for pane := range ui.currentFilterMessages[ui.currentTopic.Topic] { + if pane > len(ui.uilists[uiMessages]) { + continue + } + nbPerPage := (ui.getNbPerPage() / len(ui.currentFilterMessages[ui.currentTopic.Topic])) - 1 + c := ui.currentFilterMessages[ui.currentTopic.Topic][pane] + if c == nil { + c = &tat.MessageCriteria{} + } + c.Skip = ui.uilists[uiMessages][pane].page * nbPerPage + c.Limit = nbPerPage + c.Topic = ui.currentTopic.Topic + c.OnlyMsgRoot = "true" + ui.updateMessagesPane(pane, c) + delta := int64((time.Now().UnixNano() - start) / 1000000) + ui.lastRefresh.Text = fmt.Sprintf("%s (%dms)", time.Now().Format(time.Stamp), delta) + ui.render() + } +} + +func (ui *tatui) updateMessagesPane(pane int, criteria *tat.MessageCriteria) { + + // check if ui.uilists[uiMessages] has changed + if pane >= len(ui.uilists[uiMessages]) { + return + } + + messagesJSON, err := internal.Client().MessageList(criteria.Topic, criteria) + if err != nil { + ui.msg.Text = err.Error() + return + } + var strs []string + for _, msg := range messagesJSON.Messages { + strs = append(strs, ui.formatMessage(msg, true)) + } + + ui.uilists[uiMessages][pane].list.Items = strs + ui.currentListMessages[pane] = messagesJSON.Messages + ui.msg.Text = "" + if ui.selectedPaneMessages == pane { + ui.addMarker(ui.uilists[uiMessages][pane], pane) + } + ui.render() +} + +func (ui *tatui) formatMessage(msg tat.Message, withColor bool) string { + start := "" + end := "" + colorUsername := "" + colorLabel := "" + if withColor { + start = "[" + end = "]" + colorUsername = "(fg-cyan)" + colorLabel = "(fg-blue)" + } + text := fmt.Sprintf("%s ", time.Unix(int64(msg.DateCreation), 0).Format(time.Stamp)) + if !strings.Contains(ui.uiTopicCommands[ui.currentTopic.Topic], " /hide-usernames") { + text += fmt.Sprintf("%s%s%s%s ", start, msg.Author.Username, end, colorUsername) + } + + if msg.NbReplies > 0 { + text += fmt.Sprintf("%s ", ui.getNbMsg(msg.NbReplies)) + } + + if msg.NbVotesUP > 0 { + text += fmt.Sprintf("%d☝ ", msg.NbVotesUP) + } + + if msg.NbVotesDown > 0 { + text += fmt.Sprintf("%d☟ ", msg.NbVotesDown) + } + + if msg.NbLikes > 0 { + text += fmt.Sprintf("%d♡ ", msg.NbLikes) + } + + for _, label := range msg.Labels { + ccolor := "" + if withColor { + ccolor = colorLabel + if label.Text == "UP" || label.Text == "done" || label.Text == "Success" { + ccolor = "(fg-green)" + } else if label.Text == "AL" || label.Text == "open" || label.Text == "Fail" { + ccolor = "(fg-red)" + } else if strings.HasPrefix(label.Text, "doing") || label.Text == "Building" { + ccolor = "(fg-blue)" + } else if label.Text == "Waiting" { + ccolor = "(fg-yellow)" + } + } + text += fmt.Sprintf("%s"+label.Text+"〉%s%s", start, end, ccolor) + } + + return fmt.Sprintf("%s%s", text, msg.Text) +} + +func (ui *tatui) getNbMsg(nb int64) string { + return "☾" + strconv.FormatInt(nb, 10) + "☽" +} + +func (ui *tatui) prepareFilterMessages(text, mode, topic string) (*tat.MessageCriteria, string) { + c := &tat.MessageCriteria{} + + for _, s := range strings.Split(text, " ") { + tuple := strings.Split(s, ":") + if len(tuple) < 2 || len(strings.TrimSpace(tuple[1])) == 0 { + continue + } + + if strings.EqualFold(tuple[0], "TreeView") { + c.TreeView = strings.Join(tuple[1:], ":") + } + if strings.EqualFold(tuple[0], "IDMessage") { + c.IDMessage = strings.Join(tuple[1:], ":") + } + if strings.EqualFold(tuple[0], "InReplyOfID") { + c.InReplyOfID = strings.Join(tuple[1:], ":") + } + if strings.EqualFold(tuple[0], "InReplyOfIDRoot") { + c.InReplyOfIDRoot = strings.Join(tuple[1:], ":") + } + if strings.EqualFold(tuple[0], "AllIDMessage") { + c.AllIDMessage = strings.Join(tuple[1:], ":") + } + if strings.EqualFold(tuple[0], "Text") { + c.Text = strings.Join(tuple[1:], ":") + } + if strings.EqualFold(tuple[0], "Topic") { + c.Topic = strings.Join(tuple[1:], ":") + } + if strings.EqualFold(tuple[0], "Label") { + c.Label = strings.Join(tuple[1:], ":") + } + if strings.EqualFold(tuple[0], "NotLabel") { + c.NotLabel = strings.Join(tuple[1:], ":") + } + if strings.EqualFold(tuple[0], "AndLabel") { + c.AndLabel = strings.Join(tuple[1:], ":") + } + if strings.EqualFold(tuple[0], "Tag") { + c.Tag = strings.Join(tuple[1:], ":") + } + if strings.EqualFold(tuple[0], "NotTag") { + c.NotTag = strings.Join(tuple[1:], ":") + } + if strings.EqualFold(tuple[0], "AndTag") { + c.AndTag = strings.Join(tuple[1:], ":") + } + if strings.EqualFold(tuple[0], "Username") { + c.Username = strings.Join(tuple[1:], ":") + } + if strings.EqualFold(tuple[0], "DateMinCreation") { + c.DateMinCreation = strings.Join(tuple[1:], ":") + } + if strings.EqualFold(tuple[0], "DateMaxCreation") { + c.DateMaxCreation = strings.Join(tuple[1:], ":") + } + if strings.EqualFold(tuple[0], "DateMinUpdate") { + c.DateMinUpdate = strings.Join(tuple[1:], ":") + } + if strings.EqualFold(tuple[0], "DateMaxUpdate") { + c.DateMaxUpdate = strings.Join(tuple[1:], ":") + } + if strings.EqualFold(tuple[0], "LimitMinNbReplies") { + c.LimitMinNbReplies = strings.Join(tuple[1:], ":") + } + if strings.EqualFold(tuple[0], "LimitMaxNbReplies") { + c.LimitMaxNbReplies = strings.Join(tuple[1:], ":") + } + if strings.EqualFold(tuple[0], "LimitMinNbVotesUP") { + c.LimitMinNbVotesUP = strings.Join(tuple[1:], ":") + } + if strings.EqualFold(tuple[0], "LimitMinNbVotesDown") { + c.LimitMinNbVotesDown = strings.Join(tuple[1:], ":") + } + if strings.EqualFold(tuple[0], "LimitMaxNbVotesUP") { + c.LimitMaxNbVotesUP = strings.Join(tuple[1:], ":") + } + if strings.EqualFold(tuple[0], "LimitMaxNbVotesDown") { + c.LimitMaxNbVotesDown = strings.Join(tuple[1:], ":") + } + } + if mode == "" { + mode = "/view" + } + ui.currentModeOnTopic[topic] = strings.TrimSpace(mode) + return c, mode + " " + topic + " " + text + " " +} + +func (ui *tatui) setFilterMessages(pane int, text, mode string) { + c, criteriaText := ui.prepareFilterMessages(text, mode, ui.currentTopic.Topic) + ui.currentFilterMessages[ui.currentTopic.Topic][pane] = c + ui.currentFilterMessagesText[ui.currentTopic.Topic][pane] = criteriaText +} + +func (ui *tatui) messagesSplit(text, mode string) { + ui.clearFilterOnCurrentTopic() + criteriaText := strings.Replace(text, mode, "", 1) + criteriaText = strings.Replace(criteriaText, "/split", "", 1) + i := 0 + for _, v := range strings.Split(criteriaText, " ") { + if strings.TrimSpace(v) == "" { + continue + } + w := strings.Replace(v, ";", " ", -1) + ui.setFilterMessages(i, w, mode) + i++ + } + ui.showMessages() + ui.applyLabelOnMsgPanes() + ui.render() +} + +func (ui *tatui) applyLabelOnMsgPanes() { + mode := ui.currentModeOnTopic[ui.currentTopic.Topic] + for k := range ui.currentFilterMessages[ui.currentTopic.Topic] { + label := strings.Split(ui.currentFilterMessagesText[ui.currentTopic.Topic][k], " ") + if len(label) > 2 { + ui.uilists[uiMessages][k].list.BorderLabel = mode + " " + strings.Join(label[1:], " ") + } else { + ui.uilists[uiMessages][k].list.BorderLabel = mode + " " + ui.currentTopic.Topic + } + } +} + +func (ui *tatui) messagesRun(text string) { + tag := strings.Replace(text, "/run ", "", -1) + ui.messagesSplit(fmt.Sprintf("tag:%s;label:open tag:%s;label:doing tag:%s;label:done", tag, tag, tag), "/run") +} + +func (ui *tatui) messagesSimpleCustomSplit(typeSplit string) { + switch typeSplit { + case "/monitoring": + ui.messagesSplit(fmt.Sprintf("label:AL label:UP notLabel:AL,UP"), typeSplit) + case "/codereview": + ui.messagesSplit(fmt.Sprintf("label:OPENED label:APPROVED label:MERGED label:DECLINED"), typeSplit) + } +} + +func (ui *tatui) monitoringActionOnMessage() { + + if _, ok := ui.uilists[uiMessages][ui.selectedPaneMessages]; !ok { + return + } + if ui.uilists[uiMessages][ui.selectedPaneMessages].position >= len(ui.currentListMessages[ui.selectedPaneMessages]) { + return + } + msg := ui.currentListMessages[ui.selectedPaneMessages][ui.uilists[uiMessages][ui.selectedPaneMessages].position] + var erradd, errdel error + + // #d04437 red open + // #14892c green done + // #5484ed blue doing + + // TODO use relabel + + if msg.ContainsLabel("AL") { + // set to doing + if !msg.ContainsLabel("UP") { + _, erradd = internal.Client().MessageLabel(msg.Topic, msg.ID, tat.Label{Text: "UP", Color: hexColorGreen}) + } + _, errdel = internal.Client().MessageUnlabel(msg.Topic, msg.ID, "AL") + } else { + // set to AL + if !msg.ContainsLabel("AL") { + _, erradd = internal.Client().MessageLabel(msg.Topic, msg.ID, tat.Label{Text: "AL", Color: hexColorRed}) + } + if msg.ContainsLabel("UP") { + _, errdel = internal.Client().MessageUnlabel(msg.Topic, msg.ID, "UP") + } + } + + ui.msg.Text = "" + if erradd != nil { + ui.msg.Text += "add:" + erradd.Error() + } + if errdel != nil { + ui.msg.Text += " del:" + errdel.Error() + return + } + msg.Text = "please wait, updating message..." + ui.render() + ui.updateMessages() +} + +func (ui *tatui) postHookRunActionOnMessage(action string, msg tat.Message) { + hook := strings.TrimSpace(viper.GetString("post-hook-run-action")) + if hook == "" { + return + } + + _, err := exec.LookPath(hook) + if err != nil { + internal.Exit("Invalid hook path for post-hook-run-action, err: %s", err.Error()) + return + } + + jsonStr, err := json.Marshal(msg) + if err != nil { + internal.Exit("Error while marshalling msg for post-hook-run-action, err: %s", err.Error()) + return + } + + cmd := exec.Command(hook, action, msg.ID, string(jsonStr)) + if e := cmd.Start(); e != nil { + internal.Exit("Error with post-hook-run-action, err: %s", err.Error()) + return + } + + ui.msg.Text = "Waiting " + hook + "for command to finish..." + err = cmd.Wait() + ui.msg.Text = fmt.Sprintf("Command finished: %v", err) +} + +func (ui *tatui) runActionOnMessage(reverse bool) { + if _, ok := ui.uilists[uiMessages][ui.selectedPaneMessages]; !ok { + return + } + if ui.uilists[uiMessages][ui.selectedPaneMessages].position >= len(ui.currentListMessages[ui.selectedPaneMessages]) { + return + } + msg := ui.currentListMessages[ui.selectedPaneMessages][ui.uilists[uiMessages][ui.selectedPaneMessages].position] + var erradd, erradd2, errdel, errdel2 error + + // #d04437 red open + // #14892c green done + // #5484ed blue doing + + action := "notdefined" + + if (msg.ContainsLabel("open") && !reverse) || + (msg.ContainsLabel("done") && reverse) { // set to doing + errdel = ui.removeLabel(msg, "open") + errdel2 = ui.removeLabel(msg, "done") + if !msg.ContainsLabel("doing") { + //_, erradd = message.Action("task", "/", msg.ID, "", "") + _, erradd = internal.Client().MessageTask(msg.Topic, msg.ID) + } + action = "doing" + } else if (msg.ContainsLabel("doing") && !reverse) || + (msg.ContainsLabel("open") && reverse) { // set to done + errdel = ui.removeLabel(msg, "doing") + errdel2 = ui.removeLabel(msg, "open") + if !msg.ContainsLabel("done") { + //_, erradd = message.Action("label", "/", msg.ID, "done", hexColorGreen) + _, erradd = internal.Client().MessageLabel(msg.Topic, msg.ID, tat.Label{Text: "done", Color: hexColorGreen}) + } + action = "done" + } else if (msg.ContainsLabel("done") && !reverse) || + (msg.ContainsLabel("doing") && reverse) { // set to open + errdel = ui.removeLabel(msg, "done") + errdel2 = ui.removeLabel(msg, "doing") + if !msg.ContainsLabel("open") { + //_, erradd = message.Action("label", "/", msg.ID, "open", hexColorRed) + _, erradd = internal.Client().MessageLabel(msg.Topic, msg.ID, tat.Label{Text: "open", Color: hexColorRed}) + } + action = "open" + } else { + _, erradd = internal.Client().MessageTask(msg.Topic, msg.ID) + action = "doing" + } + + ui.msg.Text = "" + if erradd != nil { + ui.msg.Text += "add:" + erradd.Error() + } + if erradd2 != nil { + ui.msg.Text += "add:" + erradd2.Error() + } + if errdel != nil { + ui.msg.Text += " del:" + errdel.Error() + return + } + if errdel2 != nil { + ui.msg.Text += " del:" + errdel2.Error() + return + } + ui.postHookRunActionOnMessage(action, msg) + msg.Text = "please wait, updating message..." + ui.render() + ui.updateMessages() +} + +func (ui *tatui) removeLabel(msg tat.Message, label string) error { + var err error + if label == "doing" && msg.ContainsLabel("doing") { + internal.Client().MessageUntask(msg.Topic, msg.ID) + } else { + internal.Client().MessageUnlabel(msg.Topic, msg.ID, label) + if label == "done" { + for _, l := range msg.Labels { + if strings.HasPrefix(l.Text, "done:") { + internal.Client().MessageUnlabel(msg.Topic, msg.ID, l.Text) + } + } + } + } + return err +} + +func (ui *tatui) RunExec(hookIn *config.Hook, pathHook string, sendText string) { + + if ui.current != uiMessage && ui.current != uiMessages { + return + } + + if sendText == "" && pathHook == "" { + return + } + if sendText != "" && hookIn == nil { + return + } + var hook *config.Hook + if pathHook != "" { + for _, h := range ui.hooks { + if "/sys/kbd/"+h.Shortcut == pathHook { + hook = &h + sendText = "" + break + } + } + } else { + hook = hookIn + } + + userExec := strings.Split(hook.Exec, " ") + execCMD := strings.TrimSpace(userExec[0]) + if execCMD == "" { + return + } + + _, err := exec.LookPath(execCMD) + if err != nil { + internal.Exit("Invalid exec path for post-exec-run-action, err: %s", err.Error()) + return + } + + msg := ui.currentListMessages[ui.selectedPaneMessages][ui.uilists[uiMessages][ui.selectedPaneMessages].position] + + if len(hook.Topics) > 0 && !tat.ArrayContains(hook.Topics, msg.Topic) { + return + } + + toExec := strings.Replace(hook.Exec, "$UI_SELECTED_MSG_ID", msg.ID, 1) + toExec = strings.Replace(toExec, "$UI_SELECTED_MSG_TEXT", msg.Text, 1) + toExec = strings.Replace(toExec, "$UI_SELECTED_MSG_TOPIC", msg.Topic, 1) + toExec = strings.Replace(toExec, "$UI_SELECTED_MSG_AUTHOR_USERNAME", msg.Author.Username, 1) + toExec = strings.Replace(toExec, "$UI_SELECTED_MSG_DATE_CREATION", fmt.Sprintf("%f", msg.DateCreation), 1) + toExec = strings.Replace(toExec, "$UI_SELECTED_MSG_DATE_UPDATE", fmt.Sprintf("%f", msg.DateUpdate), 1) + toExec = strings.Replace(toExec, "$UI_CURRENT_USERNAME", viper.GetString("username"), 1) + + if sendText != "" { + sendTextWithoutCMD := strings.Replace(sendText, hook.Command+" ", "", 1) + toExec = strings.Replace(toExec, "$UI_ACTION_TEXT", sendTextWithoutCMD, 1) + } + + args := []string{} + if len(toExec) > 1 { + args = strings.Split(toExec, " ") + } + + cmd := exec.Command(execCMD, args[1:]...) + if e := cmd.Start(); e != nil { + internal.Exit("Error with exec hook, err: %s", e.Error()) + return + } + + ui.msg.Text = "Waiting " + hook.Exec + " for command to finish..." + err = cmd.Wait() + if err != nil { + ui.msg.Text = fmt.Sprintf("Error:%s cmd:%s", err.Error(), strings.Join(cmd.Args, " ")) + } else { + ui.msg.Text = fmt.Sprintf("Success: %s", strings.Join(cmd.Args, " ")) + } + +} diff --git a/tatcli/ui/result.go b/tatcli/ui/result.go new file mode 100644 index 0000000..4058eb7 --- /dev/null +++ b/tatcli/ui/result.go @@ -0,0 +1,28 @@ +package ui + +import ( + "github.com/gizak/termui" +) + +func (ui *tatui) showResult(cmdResult, result string) { + ui.current = uiResult + ui.send.BorderLabel = " ✎ Action" + termui.Body.Rows = nil + + p := termui.NewPar(`Result of ` + cmdResult + `: +` + result + ` +`) + + p.Height = termui.TermHeight() - uiHeightTop - uiHeightSend + p.TextFgColor = termui.ColorWhite + p.BorderTop = true + + ui.prepareTopMenu() + termui.Body.AddRows( + termui.NewRow( + termui.NewCol(12, 0, p), + ), + ) + ui.prepareSendRow() + termui.Clear() +} diff --git a/tatcli/ui/send.go b/tatcli/ui/send.go new file mode 100644 index 0000000..1741582 --- /dev/null +++ b/tatcli/ui/send.go @@ -0,0 +1,414 @@ +package ui + +import ( + "strings" + + "github.com/gizak/termui" + "github.com/ovh/tat" + "github.com/ovh/tat/tatcli/internal" + "github.com/ovh/tat/tatcli/message" + "github.com/spf13/viper" +) + +func (ui *tatui) initSend() { + p := termui.NewPar("") + p.Height = uiHeightSend + p.BorderLeft = false + p.BorderRight = false + p.BorderTop = true + p.BorderBottom = false + p.TextFgColor = termui.ColorWhite + p.BorderFg = termui.ColorCyan + p.BorderLabel = " ✎ Action " + ui.send = p +} + +func (ui *tatui) autocomplete() { + keys := []string{ + "/clear", + "/codereview", + "/favorites", + "/filter", + "/filter-topics", + "/filter-messages", + "/help", + "/hide-top", + "/hide-bottom", + "/hide-usernames", + "/label", + "/label FFFFFF yourLabel", + "/like", + "/mode", + "/monitoring", + "/open", + "/open-links", + "/quit", + "/run", + "/set-tatwebui-url", + "/save", + "/split", + "/task", + "/topics", + "/toggle-top", + "/toggle-bottom", + "/toggle-usernames", + "/unlabel", + "/unlabel yourLabel", + "/unlike", + "/untask", + "/unread", + "/unvoteup", + "/unvotedown", + "/version", + "/voteup", + "/votedown", + } + for _, h := range ui.hooks { + keys = append(keys, h.Command) + } + if strings.HasPrefix(ui.send.Text, "/") { + for _, key := range keys { + if key == ui.send.Text { + continue + } + if strings.HasPrefix(key, ui.send.Text) { + ui.send.Text = key + " " + ui.render() + break + } + } + } +} + +func (ui *tatui) processMsg() { + ui.history = append(ui.history, ui.send.Text) + ui.currentPosHistory = len(ui.history) + if strings.HasPrefix(ui.send.Text, "/") { + ui.processCmd() + return + } + if ui.current == uiMessage || ui.current == uiMessages { + ui.sendMsg() + } +} + +func (ui *tatui) processCmd() { + switch ui.send.Text { + case "/clear": + ui.send.Text = "" + ui.clearUI() + return + case "/favorites": + ui.send.Text = "" + ui.showFavoritesTopics() + return + case "/help", "/home": + ui.send.Text = "" + ui.showHome() + return + case "/me": + ui.send.Text = "" + ui.showMe() + return + case "/quit": + ui.send.Text = "" + termui.StopLoop() + case "/save": + ui.send.Text = "" + ui.saveConfig() + return + case "/topics": + ui.send.Text = "" + ui.showTopics() + return + case "/toggle-top": + ui.send.Text = "" + ui.toggleTopMenu(false) + return + case "/toggle-bottom": + ui.send.Text = "" + ui.toggleActionBox(false) + return + case "/hide-top": + ui.send.Text = "" + ui.toggleTopMenu(true) + return + case "/hide-bottom": + ui.send.Text = "" + ui.toggleActionBox(true) + return + case "/unread": + ui.send.Text = "" + ui.showUnreadTopics() + return + case "/version": + ui.send.Text = "" + ui.showVersion() + return + } + + if strings.HasPrefix(ui.send.Text, "/set-tatwebui-url ") { + ui.setTatWebUIURL(ui.send.Text) + ui.send.Text = "" + return + } else if ui.current == uiMessages && (strings.HasPrefix(ui.send.Text, "/split ")) { + ui.messagesSplit(ui.send.Text, "/view") + ui.send.Text = "" + return + } else if (ui.current == uiMessages || ui.current == uiTopics) && + (ui.send.Text == "/codereview" || ui.send.Text == "/monitoring") { + ui.messagesSimpleCustomSplit(ui.send.Text) + ui.send.Text = "" + return + } else if ui.current == uiMessages && (strings.HasPrefix(ui.send.Text, "/run ")) { + ui.messagesRun(ui.send.Text) + ui.send.Text = "" + return + } else if ui.current == uiMessages && (strings.HasPrefix(ui.send.Text, "/mode ")) { + ui.setMode(ui.send.Text) + ui.send.Text = "" + return + } else if ui.current == uiMessages && (strings.HasPrefix(ui.send.Text, "/filter-messages ") || strings.HasPrefix(ui.send.Text, "/filter ")) { + ui.setFilterMessages(ui.selectedPaneMessages, ui.send.Text, "/view") + ui.updateMessages() + ui.send.Text = "" + return + } else if ui.current == uiTopics && (strings.HasPrefix(ui.send.Text, "/filter-topics ") || strings.HasPrefix(ui.send.Text, "/filter ")) { + ui.setFilterTopics() + ui.send.Text = "" + return + } else if ui.current == uiMessage || ui.current == uiMessages { + ui.processCmdOnMessage() + ui.send.Text = "" + return + } +} + +func (ui *tatui) processCmdOnMessage() { + if ui.send.Text == "/open" { + ui.openInTatwebui() + } else if ui.send.Text == "/open-links" { + ui.openLinksInBrowser() + } else if ui.send.Text == "/toggle-usernames" { + ui.toggleUsernames(false) + } else if ui.send.Text == "/hide-usernames" { + ui.toggleUsernames(true) + } else if strings.HasPrefix(ui.send.Text, "/label ") { + ui.sendLabel() + } else if strings.HasPrefix(ui.send.Text, "/unlabel ") { + ui.sendUnlabel() + } else if strings.HasPrefix(ui.send.Text, "/vote") || + strings.HasPrefix(ui.send.Text, "/like") || + strings.HasPrefix(ui.send.Text, "/unlike") || + strings.HasPrefix(ui.send.Text, "/task") || + strings.HasPrefix(ui.send.Text, "/untask") || + strings.HasPrefix(ui.send.Text, "/unvote") { + // /voteup, /votedown, /unvoteup, /unvotedown, /like, /unlike, /task, /untask + ui.sendSimpleActionMsg() + } + + for _, h := range ui.hooks { + if strings.HasPrefix(ui.send.Text, h.Command) { + ui.RunExec(&h, "", ui.send.Text) + } + } + + ui.send.Text = "" + ui.render() +} + +func (ui *tatui) sendSimpleActionMsg() { + t := strings.TrimSpace(ui.send.Text[1:]) + + var err error + var msg *tat.MessageJSONOut + switch t { + case "voteup": + msg, err = internal.Client().MessageVoteUP(ui.currentTopic.Topic, ui.currentListMessages[ui.selectedPaneMessages][ui.uilists[uiMessages][ui.selectedPaneMessages].position].ID) + case "votedown": + msg, err = internal.Client().MessageVoteDown(ui.currentTopic.Topic, ui.currentListMessages[ui.selectedPaneMessages][ui.uilists[uiMessages][ui.selectedPaneMessages].position].ID) + case "unvoteup": + msg, err = internal.Client().MessageUnVoteUP(ui.currentTopic.Topic, ui.currentListMessages[ui.selectedPaneMessages][ui.uilists[uiMessages][ui.selectedPaneMessages].position].ID) + case "unvotedown": + msg, err = internal.Client().MessageUnVoteDown(ui.currentTopic.Topic, ui.currentListMessages[ui.selectedPaneMessages][ui.uilists[uiMessages][ui.selectedPaneMessages].position].ID) + case "like": + msg, err = internal.Client().MessageLike(ui.currentTopic.Topic, ui.currentListMessages[ui.selectedPaneMessages][ui.uilists[uiMessages][ui.selectedPaneMessages].position].ID) + case "unlike": + msg, err = internal.Client().MessageUnlike(ui.currentTopic.Topic, ui.currentListMessages[ui.selectedPaneMessages][ui.uilists[uiMessages][ui.selectedPaneMessages].position].ID) + case "task": + msg, err = internal.Client().MessageTask(ui.currentTopic.Topic, ui.currentListMessages[ui.selectedPaneMessages][ui.uilists[uiMessages][ui.selectedPaneMessages].position].ID) + case "untask": + msg, err = internal.Client().MessageUntask(ui.currentTopic.Topic, ui.currentListMessages[ui.selectedPaneMessages][ui.uilists[uiMessages][ui.selectedPaneMessages].position].ID) + } + + if err != nil { + ui.msg.Text = err.Error() + } else { + ui.uilists[uiMessages][ui.selectedPaneMessages].list.Items[ui.uilists[uiMessages][ui.selectedPaneMessages].position] = ui.formatMessage(msg.Message, true) + ui.addMarker(ui.uilists[uiMessages][ui.selectedPaneMessages], ui.selectedPaneMessages) + } + if msg.Info != "" { + ui.msg.Text = msg.Info + } +} + +func (ui *tatui) sendLabel() { + if len(strings.TrimSpace(ui.send.Text)) == 0 { + return + } + + // "/label " : 6 char + t := ui.send.Text[6:] + // /label ###### text + color := t[0:strings.Index(t, " ")] + text := t[strings.Index(t, " ")+1:] + + msg, err := internal.Client().MessageLabel(ui.currentTopic.Topic, ui.currentListMessages[ui.selectedPaneMessages][ui.uilists[uiMessages][ui.selectedPaneMessages].position].ID, tat.Label{Text: text, Color: color}) + if err != nil { + ui.msg.Text = err.Error() + } + if msg.Info != "" { + ui.msg.Text = msg.Info + } +} + +func (ui *tatui) sendUnlabel() { + if len(strings.TrimSpace(ui.send.Text)) == 0 { + return + } + + // "/unlabel " : 8 char + labelToRemove := strings.TrimSpace(ui.send.Text[8:]) + msg, err := internal.Client().MessageUnlabel(ui.currentTopic.Topic, ui.currentListMessages[ui.selectedPaneMessages][ui.uilists[uiMessages][ui.selectedPaneMessages].position].ID, labelToRemove) + if err != nil { + ui.msg.Text = err.Error() + } + if msg.Info != "" { + ui.msg.Text = msg.Info + } +} + +func (ui *tatui) clearUI() { + ui.uiTopicCommands[ui.currentTopic.Topic] = "" + if ui.current == uiTopics { + ui.currentFilterTopics = &tat.TopicCriteria{} + ui.msg.Text = "filters on topics cleared" + ui.updateTopics() + } else if ui.current == uiMessages { + ui.clearFilterOnCurrentTopic() + ui.msg.Text = "filters on messages cleared" + ui.showMessages() + } +} + +func (ui *tatui) clearFilterOnCurrentTopic() { + ui.uilists[uiMessages] = make(map[int]*uilist) + ui.currentFilterMessages[ui.currentTopic.Topic] = make(map[int]*tat.MessageCriteria) + ui.currentFilterMessages[ui.currentTopic.Topic][0] = nil + ui.currentFilterMessagesText[ui.currentTopic.Topic] = make(map[int]string) + ui.currentFilterMessagesText[ui.currentTopic.Topic][0] = "" + ui.currentModeOnTopic[ui.currentTopic.Topic] = "/view" +} + +func (ui *tatui) setFilterTopics() { + c := &tat.TopicCriteria{} + + for _, s := range strings.Split(ui.send.Text, " ") { + tuple := strings.Split(s, ":") + if len(tuple) != 2 || len(strings.TrimSpace(tuple[1])) == 0 { + continue + } + + if strings.EqualFold(tuple[0], "IDTopic") { + c.IDTopic = tuple[1] + } + if strings.EqualFold(tuple[0], "Topic") { + c.Topic = tuple[1] + } + if strings.EqualFold(tuple[0], "Description") { + c.Description = tuple[1] + } + if strings.EqualFold(tuple[0], "DateMinCreation") { + c.DateMinCreation = tuple[1] + } + if strings.EqualFold(tuple[0], "DateMaxCreation") { + c.DateMaxCreation = tuple[1] + } + if strings.EqualFold(tuple[0], "GetForTatAdmin") { + c.GetForTatAdmin = tuple[1] + } + if strings.EqualFold(tuple[0], "Group") { + c.Group = tuple[1] + } + } + + ui.uilists[uiTopics][0].list.BorderLabel = ui.uilists[uiTopics][0].list.BorderLabel + " filter on " + ui.send.Text + " " + ui.currentFilterTopics = c + ui.switchBox() + ui.updateTopics() +} + +func (ui *tatui) showMe() { + ui.msg.Text = "" + body, err := internal.Client().UserMe() + if err != nil { + ui.msg.Text = err.Error() + return + } + + out, err := tat.Sprint(body) + if err != nil { + ui.msg.Text = err.Error() + return + } + + ui.showResult("tatcli user me -> GET on /user/me ", string(out)) +} + +func (ui *tatui) showVersion() { + ui.msg.Text = "" + body, err := internal.Client().Version() + if err != nil { + ui.msg.Text = err.Error() + return + } + ui.showResult("tatcli version -> GET on "+viper.GetString("url")+"/version ", string(body)) + ui.msg.Text = "Tatcli:" + tat.Version +} + +func (ui *tatui) sendMsg() { + if ui.current != uiMessage && ui.current != uiMessages { + return + } + if len(strings.TrimSpace(ui.send.Text)) == 0 { + return + } + var err error + var msg *tat.MessageJSONOut + switch ui.current { + case uiMessages: + msg, err = message.Create(ui.currentTopic.Topic, ui.send.Text) + case uiMessage: + msg, err = internal.Client().MessageReply(ui.currentTopic.Topic, ui.currentMessage.ID, ui.send.Text) + } + if err != nil { + ui.msg.Text = err.Error() + return + } + if msg.Info != "" { + ui.msg.Text = msg.Info + } + ui.send.Text = "" + ui.render() + ui.updateMessages() +} + +func (ui *tatui) setMode(mode string) { + modeValue := strings.TrimSpace(strings.Replace(mode, "/mode ", "", 1)) + if !strings.HasPrefix(modeValue, "/") { + modeValue = "/" + modeValue + } + ui.currentModeOnTopic[ui.currentTopic.Topic] = modeValue + ui.msg.Text = "Mode " + ui.currentModeOnTopic[ui.currentTopic.Topic] + " activated on topic " + ui.currentTopic.Topic + ui.applyLabelOnMsgPanes() +} diff --git a/tatcli/ui/topics.go b/tatcli/ui/topics.go new file mode 100644 index 0000000..6f4faf9 --- /dev/null +++ b/tatcli/ui/topics.go @@ -0,0 +1,169 @@ +package ui + +import ( + "fmt" + "time" + + "github.com/gizak/termui" + "github.com/ovh/tat" + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/viper" +) + +func (ui *tatui) showUnreadTopics() { + ui.current = uiTopics + ui.onlyFavorites = "false" + ui.onlyUnread = true + ui.showTopics() +} + +func (ui *tatui) showFavoritesTopics() { + ui.current = uiTopics + ui.onlyFavorites = "true" + ui.onlyUnread = false + ui.showTopics() +} + +func (ui *tatui) showTopics() { + ui.current = uiTopics + ui.selectedPane = uiTopics + ui.send.BorderLabel = " ✎ Action " + ui.msg.Text = "tab or enter to select topic" + + termui.Body.Rows = nil + + ui.initTopics() + ui.updateTopics() + + go func() { + for { + if ui.current != uiTopics { + break + } + time.Sleep(10 * time.Second) + mutex.Lock() + ui.updateTopics() + mutex.Unlock() + } + }() + + ui.uilists[uiTopics][0].list.BorderRight = false + + ui.prepareTopMenu() + + termui.Body.AddRows( + termui.NewRow( + termui.NewCol(12, 0, ui.uilists[uiTopics][0].list), + ), + ) + ui.prepareSendRow() + termui.Clear() + ui.colorizedPanes() + ui.render() +} + +func (ui *tatui) initTopics() { + strs := []string{"[Loading...](fg-black,bg-white)"} + + ls := termui.NewList() + ls.BorderTop, ls.BorderLeft, ls.BorderRight, ls.BorderBottom = true, false, false, false + ls.Items = strs + ls.ItemFgColor = termui.ColorWhite + if ui.onlyFavorites == "true" { + ls.BorderLabel = " ★ Favorites Topics ★ " + } else if ui.onlyUnread { + ls.BorderLabel = " ✉ Unread Topics ✉ " + } else { + ls.BorderLabel = " All Topics " + } + + ls.Width = 25 + ls.Y = 0 + ls.Height = termui.TermHeight() - uiHeightTop - uiHeightSend + + m := make(map[int]*uilist) + m[0] = &uilist{uiType: uiTopics, list: ls, position: 0, page: 0, update: ui.updateTopics} + ui.uilists[uiTopics] = m +} + +func (ui *tatui) enterTopic() { + ui.currentTopic = ui.currentListTopic[ui.uilists[uiTopics][0].position] + ui.showMessages() +} + +func (ui *tatui) updateTopics() { + start := time.Now().UnixNano() + nbPerPage := ui.getNbPerPage() + + c := ui.currentFilterTopics + if c == nil { + c = &tat.TopicCriteria{} + } + if ui.onlyUnread { + c.Skip = 0 + c.Limit = 1000 + } else { + c.Skip = ui.uilists[uiTopics][0].page * nbPerPage + c.Limit = nbPerPage + } + + c.OnlyFavorites = ui.onlyFavorites + c.GetNbMsgUnread = "true" + + topicsJSON, err := internal.Client().TopicList(c) + if err != nil { + ui.msg.Text = err.Error() + return + } + var strs []string + topics := []tat.Topic{} + ui.currentListUnreadTopics = topicsJSON.TopicsMsgUnread + privateTasksTopic := fmt.Sprintf("/Private/%s/Tasks", viper.GetString("username")) + for _, topic := range topicsJSON.Topics { + if topic.Topic == privateTasksTopic { + continue + } + + topicLine, isUnread := ui.formatTopic(topic, true) + if !ui.onlyUnread || isUnread { + strs = append(strs, topicLine) + topics = append(topics, topic) + } + } + if ui.onlyUnread { + max := nbPerPage - 1 + if len(topics) < nbPerPage { + max = len(topics) - 1 + } + if ui.uilists[uiTopics][0].page*nbPerPage > len(topics) { + return + } + ui.currentListTopic = topics[ui.uilists[uiTopics][0].page*nbPerPage : max] + ui.uilists[uiTopics][0].list.Items = strs[ui.uilists[uiTopics][0].page*nbPerPage : max] + } else { + ui.currentListTopic = topics + ui.uilists[uiTopics][0].list.Items = strs + } + + ui.msg.Text = "" + ui.addMarker(ui.uilists[uiTopics][0], 0) + delta := int64((time.Now().UnixNano() - start) / 1000000) + ui.lastRefresh.Text = fmt.Sprintf("%s (%dms)", time.Now().Format(time.Stamp), delta) + ui.render() +} + +func (ui *tatui) formatTopic(topic tat.Topic, withColor bool) (string, bool) { + textUnread := "" + for topicName, unread := range ui.currentListUnreadTopics { + if topic.Topic == topicName && unread > 0 { + if withColor { + textUnread += fmt.Sprintf(" [✉](fg-red)") + } else { + textUnread += fmt.Sprintf(" ✉ ") + } + break + } + } + + return topic.Topic + textUnread, textUnread != "" +} diff --git a/tatcli/ui/ui.go b/tatcli/ui/ui.go new file mode 100644 index 0000000..21ae989 --- /dev/null +++ b/tatcli/ui/ui.go @@ -0,0 +1,315 @@ +package ui + +import ( + "strings" + "sync" + "time" + + "github.com/gizak/termui" + "github.com/ovh/tat" + "github.com/ovh/tat/tatcli/config" + "github.com/ovh/tat/tatcli/internal" +) + +var mutex = &sync.Mutex{} + +// tatui wrapper designed for dashboard creation +type tatui struct { + header *termui.Par + msg *termui.Par + lastRefresh *termui.Par + homeLeft *termui.Par + homeRight *termui.Par + send *termui.Par + + selectedPane int + selectedPaneMessages int + current int + + onlyFavorites string + onlyUnread bool + + currentListTopic []tat.Topic + currentListUnreadTopics map[string]int + currentTopic tat.Topic + currentListMessages map[int][]tat.Message + currentMessage tat.Message + currentFilterTopics *tat.TopicCriteria + currentFilterMessages map[string]map[int]*tat.MessageCriteria + currentFilterMessagesText map[string]map[int]string + currentModeOnTopic map[string]string + history []string + currentPosHistory int + uiTopicCommands map[string]string + firstCallMessages bool + hooks []config.Hook + + uilists map[int]map[int]*uilist +} + +type uilist struct { + uiType int + list *termui.List + position, page int + update func() +} + +const ( + uiTopics int = iota + uiMessages + uiMessage + uiHome + uiResult + uiActionBox +) + +var ( + uiHeightTop = 1 + uiHeightSend = 2 + currentPosHistory = 0 +) + +const ( + hexColorGreen = "#14892c" + hexColorRed = "#d04437" + hexColorBlue = "#5484ed" +) + +func (ui *tatui) init(args []string) { + if err := termui.Init(); err != nil { + panic(err) + } + + // do not display log in ui mode + tat.DebugLogFunc = func(string, ...interface{}) {} + tat.ErrorLogFunc = func(string, ...interface{}) {} + + ui.firstCallMessages = false + ui.uilists = make(map[int]map[int]*uilist) + ui.currentFilterMessages = make(map[string]map[int]*tat.MessageCriteria) + ui.currentFilterMessagesText = make(map[string]map[int]string) + ui.currentListMessages = make(map[int][]tat.Message) + ui.currentModeOnTopic = make(map[string]string) + ui.uiTopicCommands = make(map[string]string) + ui.history = []string{} + + commands := ui.loadArgs(args) + ui.loadConfig() + ui.initHeader() + ui.initMsg() + ui.initLastRefresh() + ui.initHome() + ui.initSend() + if ui.currentTopic.Topic != "" { + ui.showTopics() + ui.updateTopics() + ui.showMessages() + for !ui.firstCallMessages { + time.Sleep(1 * time.Second) + } + ui.execCommands(commands) + } else { + ui.showHome() + } + + ui.initHandles() +} + +func (ui *tatui) render() { + termui.Render(termui.Body) +} + +func (ui *tatui) draw(i int) { + termui.Body.Align() + termui.Render(termui.Body) +} + +func (ui *tatui) initHeader() { + p := termui.NewPar("TAT ➠ topics: (f)avorites - un(r)ead - (a)ll | (h)ome | (q)uit") + p.Height = uiHeightTop + p.TextFgColor = termui.ColorWhite + p.Border = false + ui.header = p +} + +func (ui *tatui) getNbPerPage() int { + if _, ok := ui.uilists[uiTopics]; ok { + return ui.uilists[uiTopics][0].list.Height - 1 + } + return 1 +} + +func (ui *tatui) isOnActionBox() bool { + return ui.selectedPane == uiActionBox +} + +func (ui *tatui) initMsg() { + p := termui.NewPar("") + p.Height = uiHeightTop + p.TextFgColor = termui.ColorWhite + p.BorderTop, p.BorderLeft, p.BorderRight, p.BorderBottom = false, false, false, false + ui.msg = p +} + +func (ui *tatui) initLastRefresh() { + p := termui.NewPar("") + p.Height = uiHeightTop + p.TextFgColor = termui.ColorWhite + p.BorderTop, p.BorderLeft, p.BorderRight, p.BorderBottom = false, false, false, false + ui.lastRefresh = p +} + +func (ui *tatui) prepareTopMenu() { + if !strings.Contains(ui.uiTopicCommands[ui.currentTopic.Topic], " /hide-top") { + termui.Body.AddRows( + termui.NewRow( + termui.NewCol(4, 0, ui.header), + termui.NewCol(6, 0, ui.msg), + termui.NewCol(2, 0, ui.lastRefresh), + ), + ) + } +} + +func (ui *tatui) prepareSendRow() { + if strings.Contains(ui.uiTopicCommands[ui.currentTopic.Topic], " /hide-bottom") { + return + } + if !strings.Contains(ui.uiTopicCommands[ui.currentTopic.Topic], " /hide-top") { + termui.Body.AddRows( + termui.NewRow( + termui.NewCol(12, 0, ui.send), + ), + ) + } else { + termui.Body.AddRows( + termui.NewRow( + termui.NewCol(5, 0, ui.send), + termui.NewCol(5, 0, ui.msg), + termui.NewCol(2, 0, ui.lastRefresh), + ), + ) + } +} + +func (ui *tatui) toggleActionBox(forceHide bool) { + ui.toggleActionOnTopic(" /hide-bottom", forceHide) + + if !strings.Contains(ui.uiTopicCommands[ui.currentTopic.Topic], " /hide-bottom") { + uiHeightSend = 2 + } else { + uiHeightSend = 0 + } + ui.reloadCurrent() +} + +func (ui *tatui) toggleTopMenu(forceHide bool) { + ui.toggleActionOnTopic(" /hide-top", forceHide) + + if !strings.Contains(ui.uiTopicCommands[ui.currentTopic.Topic], " /hide-top") { + uiHeightTop = 1 + ui.msg.BorderTop = false + ui.lastRefresh.BorderTop = false + ui.msg.Height = uiHeightTop + ui.lastRefresh.Height = uiHeightTop + } else { + uiHeightTop = 0 + ui.msg.BorderTop = true + ui.lastRefresh.BorderTop = true + ui.msg.Height = uiHeightSend + ui.lastRefresh.Height = uiHeightSend + } + ui.reloadCurrent() +} + +func (ui *tatui) toggleActionOnTopic(action string, forceHide bool) { + if forceHide { + if !strings.Contains(ui.uiTopicCommands[ui.currentTopic.Topic], action) { + ui.uiTopicCommands[ui.currentTopic.Topic] += action + } + } else { + if strings.Contains(ui.uiTopicCommands[ui.currentTopic.Topic], action) { + ui.uiTopicCommands[ui.currentTopic.Topic] = strings.Replace(ui.uiTopicCommands[ui.currentTopic.Topic], action, "", -1) + } else { + ui.uiTopicCommands[ui.currentTopic.Topic] += action + } + } +} + +func (ui *tatui) reloadCurrent() { + switch ui.current { + case uiMessage: + ui.showMessage() + case uiMessages: + ui.showMessages() + case uiHome, uiResult: + ui.showHome() + case uiTopics: + ui.showTopics() + } + ui.render() +} + +// arrayContains return true if element is in array +func arrayContains(array []string, element string) bool { + for _, cur := range array { + if cur == element { + return true + } + } + return false +} + +// loadArgs load args form command line and return topic, filter, command +func (ui *tatui) loadArgs(args []string) []string { + // example : + // /YourTopic/SubTopic /split label:open label:doing label:done /save + // /YourTopic/SubTopic /run CD + // /YourTopic/SubTopic /run CD /save + // /YourTopic/SubTopic /monitoring /save + if len(args) < 1 { + return []string{} + } + + topicName := "" + if strings.HasPrefix(args[0], "/") { + topicName = args[0] + } + c := &tat.TopicCriteria{Topic: strings.TrimSpace(topicName)} + + //topicsB, err := internal.Request("GET", 200, topic.TopicsListURL(c), nil) + topicsJSON, err := internal.Client().TopicList(c) + if err != nil { + internal.Exit("Error while loading topic %s error:%s", args[0], err.Error()) + } + + if len(topicsJSON.Topics) != 1 { + internal.Exit("Args on tatcli ui should begin with topic name. Please check it on %s", args[0]) + } + + ui.currentTopic = topicsJSON.Topics[0] + + commands := []string{} + cmd := "" + for i := 1; i < len(args); i++ { + if strings.HasPrefix(args[i], "/") { + if cmd != "" { + commands = append(commands, cmd) + } + cmd = args[i] + } else { + cmd += " " + args[i] + } + } + if cmd != "" { + commands = append(commands, cmd) + } + return commands +} + +func (ui *tatui) execCommands(commands []string) { + for i := 0; i < len(commands); i++ { + ui.send.Text = commands[i] + ui.processCmd() + } +} diff --git a/tatcli/update/cmd.go b/tatcli/update/cmd.go new file mode 100644 index 0000000..d6bc14d --- /dev/null +++ b/tatcli/update/cmd.go @@ -0,0 +1,90 @@ +package update + +import ( + "fmt" + "net/http" + + "github.com/google/go-github/github" + "github.com/inconshreveable/go-update" + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" +) + +// used by CI to inject architecture (linux-amd64, etc...) at build time +var architecture string +var urlGitubReleases = "https://github.com/ovh/tat/releases" + +// Cmd update +var Cmd = &cobra.Command{ + Use: "update", + Short: "Update tatcli to the latest release version: tatcli update", + Long: `tatcli update`, + Aliases: []string{"up"}, + Run: func(cmd *cobra.Command, args []string) { + doUpdate("", architecture) + }, +} + +func getURLArtifactFromGithub(architecture string) string { + client := github.NewClient(nil) + release, resp, err := client.Repositories.GetLatestRelease("ovh", "tat") + if err != nil { + internal.Exit("Repositories.GetLatestRelease returned error: %v\n%v", err, resp.Body) + } + + if len(release.Assets) > 0 { + for _, asset := range release.Assets { + if *asset.Name == "tatcli-"+architecture { + return *asset.BrowserDownloadURL + } + } + } + + text := "Invalid Artifacts on latest release. Please try again in few minutes.\n" + text += "If the problem persists, please open an issue on https://github.com/ovh/tat/issues\n" + internal.Exit(text) + return "" +} + +func getContentType(resp *http.Response) string { + for k, v := range resp.Header { + if k == "Content-Type" && len(v) >= 1 { + return v[0] + } + } + return "" +} + +func doUpdate(baseurl, architecture string) { + if architecture == "" { + text := "You seem to have a custom build of tatcli.\n" + text += "Please download latest release on %s\n" + internal.Exit(text, urlGitubReleases) + } + + url := getURLArtifactFromGithub(architecture) + if internal.Debug { + fmt.Printf("Url to update tatcli: %s\n", url) + } + + resp, err := http.Get(url) + if err != nil { + internal.Exit("Error when downloading tatcli from url: %s, err:%s\n", url, err.Error()) + } + + if contentType := getContentType(resp); contentType != "application/octet-stream" { + fmt.Printf("Url: %s\n", url) + internal.Exit("Invalid Binary (Content-Type: %s). Please try again or download it manually from %s\n", contentType, urlGitubReleases) + } + + if resp.StatusCode != 200 { + internal.Exit("Error http code: %d, url called: %s\n", resp.StatusCode, url) + } + + fmt.Printf("Getting latest release from : %s ...\n", url) + defer resp.Body.Close() + if err = update.Apply(resp.Body, update.Options{}); err != nil { + internal.Exit("Error when updating tatcli from url: %s err:%s\n", url, err.Error()) + } + fmt.Println("Update done.") +} diff --git a/tatcli/user/add.go b/tatcli/user/add.go new file mode 100644 index 0000000..7c148b7 --- /dev/null +++ b/tatcli/user/add.go @@ -0,0 +1,28 @@ +package user + +import ( + "strings" + + "github.com/ovh/tat" + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" +) + +var cmdUserAdd = &cobra.Command{ + Use: "add", + Short: "Add a user: tatcli user add ", + Run: func(cmd *cobra.Command, args []string) { + if len(args) >= 3 { + out, err := internal.Client().UserAdd(tat.UserCreateJSON{ + Username: args[0], + Fullname: strings.Join(args[2:], " "), + Email: args[1], + Callback: "tatcli --url=:scheme://:host::port:path user verify --save :username :token", + }) + internal.Check(err) + internal.Print(out) + } else { + internal.Exit("Invalid argument to add user: tatcli user add --help\n") + } + }, +} diff --git a/tatcli/user/add_contact.go b/tatcli/user/add_contact.go new file mode 100644 index 0000000..f9271d4 --- /dev/null +++ b/tatcli/user/add_contact.go @@ -0,0 +1,20 @@ +package user + +import ( + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" +) + +var cmdUserAddContact = &cobra.Command{ + Use: "addContact", + Short: "Add a contact: tatcli user addContact ", + Run: func(cmd *cobra.Command, args []string) { + if len(args) == 1 { + out, err := internal.Client().UserAddContact(args[0]) + internal.Check(err) + internal.Print(out) + } else { + internal.Exit("Invalid argument to add contact: tatcli user addContact --help\n") + } + }, +} diff --git a/tatcli/user/add_favorite_tag.go b/tatcli/user/add_favorite_tag.go new file mode 100644 index 0000000..41a323d --- /dev/null +++ b/tatcli/user/add_favorite_tag.go @@ -0,0 +1,20 @@ +package user + +import ( + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" +) + +var cmdUserAddFavoriteTag = &cobra.Command{ + Use: "addFavoriteTag", + Short: "Add a favorite Tag: tatcli user addFavoriteTag ", + Run: func(cmd *cobra.Command, args []string) { + if len(args) == 1 { + out, err := internal.Client().UserAddFavoriteTag(args[0]) + internal.Check(err) + internal.Print(out) + } else { + internal.Exit("Invalid argument: tatcli user addFavoriteTag --help\n") + } + }, +} diff --git a/tatcli/user/add_favorite_topic.go b/tatcli/user/add_favorite_topic.go new file mode 100644 index 0000000..c7e3503 --- /dev/null +++ b/tatcli/user/add_favorite_topic.go @@ -0,0 +1,20 @@ +package user + +import ( + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" +) + +var cmdUserAddFavoriteTopic = &cobra.Command{ + Use: "addFavoriteTopic", + Short: "Add a favorite Topic: tatcli user addFavoriteTopic ", + Run: func(cmd *cobra.Command, args []string) { + if len(args) == 1 { + out, err := internal.Client().UserAddFavoriteTopic(args[0]) + internal.Check(err) + internal.Print(out) + } else { + internal.Exit("Invalid argument: tatcli user addFavoriteTopic --help\n") + } + }, +} diff --git a/tatcli/user/archive.go b/tatcli/user/archive.go new file mode 100644 index 0000000..df5b081 --- /dev/null +++ b/tatcli/user/archive.go @@ -0,0 +1,19 @@ +package user + +import ( + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" +) + +var cmdUserArchive = &cobra.Command{ + Use: "archive", + Short: "Archive a user (admin only): tatcli user archive ", + Run: func(cmd *cobra.Command, args []string) { + if len(args) == 1 { + err := internal.Client().UserArchive(args[0]) + internal.Check(err) + } else { + internal.Exit("Invalid argument: tatcli user archive --help\n") + } + }, +} diff --git a/tatcli/user/check.go b/tatcli/user/check.go new file mode 100644 index 0000000..b39c2ae --- /dev/null +++ b/tatcli/user/check.go @@ -0,0 +1,40 @@ +package user + +import ( + "fmt" + "strconv" + + "github.com/ovh/tat" + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" +) + +var cmdUserCheck = &cobra.Command{ + Use: "check", + Short: "Check Private Topics and Default Group on one user (admin only): tatcli user check ", + Long: `Check Private Topics and Default Group on one user: +tatcli user check + +Example : + +tatcli check username true true + `, + Run: func(cmd *cobra.Command, args []string) { + if len(args) == 3 { + fixPrivateTopics, e1 := strconv.ParseBool(args[1]) + fixDefaultGroup, e2 := strconv.ParseBool(args[2]) + if e1 != nil || e2 != nil { + fmt.Println("Invalid argument: tatcli user check --help") + } + out, err := internal.Client().UserCheck(tat.CheckTopicsUserJSON{ + Username: args[0], + FixPrivateTopics: fixPrivateTopics, + FixDefaultGroup: fixDefaultGroup, + }) + internal.Check(err) + internal.Print(out) + } else { + internal.Exit("Invalid argument: tatcli user check --help\n") + } + }, +} diff --git a/tatcli/user/contacts.go b/tatcli/user/contacts.go new file mode 100644 index 0000000..24a4d65 --- /dev/null +++ b/tatcli/user/contacts.go @@ -0,0 +1,25 @@ +package user + +import ( + "strconv" + + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" +) + +var cmdUserContacts = &cobra.Command{ + Use: "contacts", + Short: "Get contacts presences since n seconds: tatcli user contacts ", + Run: func(cmd *cobra.Command, args []string) { + if len(args) == 1 { + seconds, err := strconv.Atoi(args[0]) + if err == nil { + out, err := internal.Client().UserContacts(seconds) + internal.Check(err) + internal.Print(out) + return + } + } + internal.Exit("Invalid argument: tatcli user contacts --help\n") + }, +} diff --git a/tatcli/user/convert_to_system.go b/tatcli/user/convert_to_system.go new file mode 100644 index 0000000..6aeefd9 --- /dev/null +++ b/tatcli/user/convert_to_system.go @@ -0,0 +1,31 @@ +package user + +import ( + "strconv" + + "github.com/ovh/tat" + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" +) + +var cmdUserConvertToSystem = &cobra.Command{ + Use: "convert", + Short: "Convert a user to a system user (admin only): tatcli user convert ", + Run: func(cmd *cobra.Command, args []string) { + if len(args) == 3 { + canWriteNotifications, err := strconv.ParseBool(args[1]) + internal.Check(err) + canListUsersAsAdmin, err := strconv.ParseBool(args[2]) + internal.Check(err) + out, err := internal.Client().UserConvertToSystem(tat.ConvertUserJSON{ + Username: args[0], + CanWriteNotifications: canWriteNotifications, + CanListUsersAsAdmin: canListUsersAsAdmin, + }) + internal.Check(err) + internal.Print(out) + } else { + internal.Exit("Invalid argument : tatcli user convert --help\n") + } + }, +} diff --git a/tatcli/user/disable_notifications_all_topics.go b/tatcli/user/disable_notifications_all_topics.go new file mode 100644 index 0000000..48bd71f --- /dev/null +++ b/tatcli/user/disable_notifications_all_topics.go @@ -0,0 +1,16 @@ +package user + +import ( + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" +) + +var cmdUserDisableNotificationsAllTopics = &cobra.Command{ + Use: "disableNotificationsAllTopics", + Short: "Disable notifications on all topics: tatcli user disableNotificationsAllTopics", + Run: func(cmd *cobra.Command, args []string) { + out, err := internal.Client().UserDisableNotificationsAllTopics() + internal.Check(err) + internal.Print(out) + }, +} diff --git a/tatcli/user/disable_notifications_topic.go b/tatcli/user/disable_notifications_topic.go new file mode 100644 index 0000000..df42950 --- /dev/null +++ b/tatcli/user/disable_notifications_topic.go @@ -0,0 +1,20 @@ +package user + +import ( + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" +) + +var cmdUserDisableNotificationsTopic = &cobra.Command{ + Use: "disableNotificationsTopic", + Short: "Disable notifications on a topic: tatcli user disableNotificationsTopic ", + Run: func(cmd *cobra.Command, args []string) { + if len(args) == 1 { + out, err := internal.Client().UserDisableNotificationsTopic(args[0]) + internal.Check(err) + internal.Print(out) + } else { + internal.Exit("Invalid argument: tatcli user disableNotificationsTopic --help\n") + } + }, +} diff --git a/tatcli/user/enable_notifications_all_topics.go b/tatcli/user/enable_notifications_all_topics.go new file mode 100644 index 0000000..54da5bf --- /dev/null +++ b/tatcli/user/enable_notifications_all_topics.go @@ -0,0 +1,16 @@ +package user + +import ( + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" +) + +var cmdUserEnableNotificationsAllTopics = &cobra.Command{ + Use: "enableNotificationsAllTopics", + Short: "Enable notifications on a topic: tatcli user enableNotificationsAllTopics", + Run: func(cmd *cobra.Command, args []string) { + out, err := internal.Client().UserEnableNotificationsAllTopics() + internal.Check(err) + internal.Print(out) + }, +} diff --git a/tatcli/user/enable_notifications_topic.go b/tatcli/user/enable_notifications_topic.go new file mode 100644 index 0000000..5c9f461 --- /dev/null +++ b/tatcli/user/enable_notifications_topic.go @@ -0,0 +1,20 @@ +package user + +import ( + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" +) + +var cmdUserEnableNotificationsTopic = &cobra.Command{ + Use: "enableNotificationsTopic", + Short: "Enable notifications on a topic: tatcli user enableNotificationsTopic ", + Run: func(cmd *cobra.Command, args []string) { + if len(args) == 1 { + out, err := internal.Client().UserEnableNotificationsTopic(args[0]) + internal.Check(err) + internal.Print(out) + } else { + internal.Exit("Invalid argument: tatcli user enableNotificationsTopic --help\n") + } + }, +} diff --git a/tatcli/user/list.go b/tatcli/user/list.go new file mode 100644 index 0000000..1b25f48 --- /dev/null +++ b/tatcli/user/list.go @@ -0,0 +1,29 @@ +package user + +import ( + "github.com/ovh/tat" + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" +) + +var withGroups bool + +func init() { + cmdUserList.Flags().BoolVarP(&withGroups, "with-groups", "g", false, "List Users with groups, admin only") +} + +var cmdUserList = &cobra.Command{ + Use: "list", + Short: "List all users: tatcli user list [] []", + Run: func(cmd *cobra.Command, args []string) { + skip, limit := internal.GetSkipLimit(args) + criteria := &tat.UserCriteria{ + Skip: skip, + Limit: limit, + WithGroups: withGroups, + } + out, err := internal.Client().UserList(criteria) + internal.Check(err) + internal.Print(out) + }, +} diff --git a/tatcli/user/me.go b/tatcli/user/me.go new file mode 100644 index 0000000..bb28ff4 --- /dev/null +++ b/tatcli/user/me.go @@ -0,0 +1,16 @@ +package user + +import ( + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" +) + +var cmdUserMe = &cobra.Command{ + Use: "me", + Short: "Get Information about you: tatcli user me", + Run: func(cmd *cobra.Command, args []string) { + out, err := internal.Client().UserMe() + internal.Check(err) + internal.Print(out) + }, +} diff --git a/tatcli/user/remove_contact.go b/tatcli/user/remove_contact.go new file mode 100644 index 0000000..4adb163 --- /dev/null +++ b/tatcli/user/remove_contact.go @@ -0,0 +1,20 @@ +package user + +import ( + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" +) + +var cmdUserRemoveContact = &cobra.Command{ + Use: "removeContact", + Short: "Remove a contact: tatcli user removeContact ", + Run: func(cmd *cobra.Command, args []string) { + if len(args) == 1 { + out, err := internal.Client().UserRemoveContact(args[0]) + internal.Check(err) + internal.Print(out) + } else { + internal.Exit("Invalid argument: tatcli user removeContact --help\n") + } + }, +} diff --git a/tatcli/user/remove_favorite_tag.go b/tatcli/user/remove_favorite_tag.go new file mode 100644 index 0000000..9718b6c --- /dev/null +++ b/tatcli/user/remove_favorite_tag.go @@ -0,0 +1,20 @@ +package user + +import ( + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" +) + +var cmdUserRemoveFavoriteTag = &cobra.Command{ + Use: "removeFavoriteTag", + Short: "Remove a favorite Tag: tatcli user removeFavoriteTag ", + Run: func(cmd *cobra.Command, args []string) { + if len(args) == 1 { + out, err := internal.Client().UserRemoveFavoriteTag(args[0]) + internal.Check(err) + internal.Print(out) + } else { + internal.Exit("Invalid argument: tatcli user removeFavoriteTag --help\n") + } + }, +} diff --git a/tatcli/user/remove_favorite_topic.go b/tatcli/user/remove_favorite_topic.go new file mode 100644 index 0000000..9fa7abc --- /dev/null +++ b/tatcli/user/remove_favorite_topic.go @@ -0,0 +1,20 @@ +package user + +import ( + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" +) + +var cmdUserRemoveFavoriteTopic = &cobra.Command{ + Use: "removeFavoriteTopic", + Short: "Remove a favorite Topic: tatcli user removeFavoriteTopic ", + Run: func(cmd *cobra.Command, args []string) { + if len(args) == 1 { + out, err := internal.Client().UserRemoveFavoriteTopic(args[0]) + internal.Check(err) + internal.Print(out) + } else { + internal.Exit("Invalid argument: tatcli user removeFavoriteTopic --help\n") + } + }, +} diff --git a/tatcli/user/rename.go b/tatcli/user/rename.go new file mode 100644 index 0000000..6f8399f --- /dev/null +++ b/tatcli/user/rename.go @@ -0,0 +1,24 @@ +package user + +import ( + "github.com/ovh/tat" + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" +) + +var cmdUserRename = &cobra.Command{ + Use: "rename", + Short: "Rename username of a user (admin only): tatcli user rename ", + Run: func(cmd *cobra.Command, args []string) { + if len(args) == 2 { + out, err := internal.Client().UserRename(tat.RenameUserJSON{ + Username: args[0], + NewUsername: args[1], + }) + internal.Check(err) + internal.Print(out) + } else { + internal.Exit("Invalid argument: tatcli user rename --help\n") + } + }, +} diff --git a/tatcli/user/reset.go b/tatcli/user/reset.go new file mode 100644 index 0000000..35499ca --- /dev/null +++ b/tatcli/user/reset.go @@ -0,0 +1,25 @@ +package user + +import ( + "github.com/ovh/tat" + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" +) + +var cmdUserReset = &cobra.Command{ + Use: "reset", + Short: "Ask for Reset a password: tatcli user reset ", + Run: func(cmd *cobra.Command, args []string) { + if len(args) == 2 { + out, err := internal.Client().UserReset(tat.UserResetJSON{ + Username: args[0], + Email: args[1], + Callback: "tatcli --url=:scheme://:host::port:path user verify --save :username :token", + }) + internal.Check(err) + internal.Print(out) + } else { + internal.Exit("Invalid argument to reset password: tatcli user reset --help\n") + } + }, +} diff --git a/tatcli/user/set_admin.go b/tatcli/user/set_admin.go new file mode 100644 index 0000000..b5c8db8 --- /dev/null +++ b/tatcli/user/set_admin.go @@ -0,0 +1,23 @@ +package user + +import ( + "github.com/ovh/tat" + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" +) + +var cmdUserSetAdmin = &cobra.Command{ + Use: "setAdmin", + Short: "Grant user to Tat admin (admin only): tatcli user setAdmin ", + Run: func(cmd *cobra.Command, args []string) { + if len(args) == 1 { + out, err := internal.Client().UserSetAdmin(tat.UsernameUserJSON{ + Username: args[0], + }) + internal.Check(err) + internal.Print(out) + } else { + internal.Exit("Invalid argument: tatcli user setAdmin --help\n") + } + }, +} diff --git a/tatcli/user/system_reset.go b/tatcli/user/system_reset.go new file mode 100644 index 0000000..a434e7a --- /dev/null +++ b/tatcli/user/system_reset.go @@ -0,0 +1,23 @@ +package user + +import ( + "github.com/ovh/tat" + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" +) + +var cmdUserResetSystem = &cobra.Command{ + Use: "resetSystemUser", + Short: "Reset password for a system user (admin only): tatcli user resetSystemUser ", + Run: func(cmd *cobra.Command, args []string) { + if len(args) == 1 { + out, err := internal.Client().UserResetSystem(tat.UsernameUserJSON{ + Username: args[0], + }) + internal.Check(err) + internal.Print(out) + } else { + internal.Exit("Invalid argument: tatcli user resetSystemUser --help\n") + } + }, +} diff --git a/tatcli/user/update.go b/tatcli/user/update.go new file mode 100644 index 0000000..8d14a17 --- /dev/null +++ b/tatcli/user/update.go @@ -0,0 +1,27 @@ +package user + +import ( + "strings" + + "github.com/ovh/tat" + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" +) + +var cmdUserUpdate = &cobra.Command{ + Use: "update", + Short: "Update Fullname and Email of a user (admin only): tatcli user update ", + Run: func(cmd *cobra.Command, args []string) { + if len(args) >= 3 { + out, err := internal.Client().UserUpdate(tat.UpdateUserJSON{ + Username: args[0], + NewEmail: args[1], + NewFullname: strings.Join(args[2:], " "), + }) + internal.Check(err) + internal.Print(out) + } else { + internal.Exit("Invalid argument: tatcli user update --help\n") + } + }, +} diff --git a/tatcli/user/update_system.go b/tatcli/user/update_system.go new file mode 100644 index 0000000..7560aa5 --- /dev/null +++ b/tatcli/user/update_system.go @@ -0,0 +1,31 @@ +package user + +import ( + "strconv" + + "github.com/ovh/tat" + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" +) + +var cmdUserUpdateSystem = &cobra.Command{ + Use: "updateSystemUser", + Short: "Update a system user (admin only): tatcli user updateSystemUser ", + Run: func(cmd *cobra.Command, args []string) { + if len(args) == 3 { + canWriteNotifications, err := strconv.ParseBool(args[1]) + internal.Check(err) + canListUsersAsAdmin, err := strconv.ParseBool(args[2]) + internal.Check(err) + out, err := internal.Client().UserUpdateSystem(tat.ConvertUserJSON{ + Username: args[0], + CanWriteNotifications: canWriteNotifications, + CanListUsersAsAdmin: canListUsersAsAdmin, + }) + internal.Check(err) + internal.Print(out) + } else { + internal.Exit("Invalid argument : tatcli user convert --help\n") + } + }, +} diff --git a/tatcli/user/user.go b/tatcli/user/user.go new file mode 100644 index 0000000..e7eeb12 --- /dev/null +++ b/tatcli/user/user.go @@ -0,0 +1,40 @@ +package user + +import ( + "github.com/spf13/cobra" +) + +func init() { + Cmd.AddCommand(cmdUserList) + Cmd.AddCommand(cmdUserMe) + Cmd.AddCommand(cmdUserContacts) + Cmd.AddCommand(cmdUserAddContact) + Cmd.AddCommand(cmdUserRemoveContact) + Cmd.AddCommand(cmdUserAddFavoriteTopic) + Cmd.AddCommand(cmdUserRemoveFavoriteTopic) + Cmd.AddCommand(cmdUserEnableNotificationsTopic) + Cmd.AddCommand(cmdUserEnableNotificationsAllTopics) + Cmd.AddCommand(cmdUserDisableNotificationsTopic) + Cmd.AddCommand(cmdUserDisableNotificationsAllTopics) + Cmd.AddCommand(cmdUserAddFavoriteTag) + Cmd.AddCommand(cmdUserRemoveFavoriteTag) + Cmd.AddCommand(cmdUserAdd) + Cmd.AddCommand(cmdUserReset) + Cmd.AddCommand(cmdUserResetSystem) + Cmd.AddCommand(cmdUserConvertToSystem) + Cmd.AddCommand(cmdUserUpdateSystem) + Cmd.AddCommand(cmdUserArchive) + Cmd.AddCommand(cmdUserRename) + Cmd.AddCommand(cmdUserUpdate) + Cmd.AddCommand(cmdUserSetAdmin) + Cmd.AddCommand(cmdUserVerify) + Cmd.AddCommand(cmdUserCheck) +} + +// Cmd user +var Cmd = &cobra.Command{ + Use: "user", + Short: "User commands: tatcli user --help", + Long: `User commands: tatcli user `, + Aliases: []string{"u"}, +} diff --git a/tatcli/user/verify.go b/tatcli/user/verify.go new file mode 100644 index 0000000..72ff423 --- /dev/null +++ b/tatcli/user/verify.go @@ -0,0 +1,50 @@ +package user + +import ( + "encoding/json" + "io/ioutil" + "os" + "path" + + "github.com/ovh/tat/tatcli/internal" + "github.com/spf13/cobra" +) + +var save bool + +func init() { + cmdUserVerify.Flags().BoolVarP(&save, "save", "s", false, "Save configuration after verify in $HOME/.tatcli/config.json") +} + +var cmdUserVerify = &cobra.Command{ + Use: "verify", + Short: "Verify account: tatcli user verify [--save] ", + Run: func(cmd *cobra.Command, args []string) { + if len(args) == 2 { + userVerify(args[0], args[1]) + } else { + internal.Exit("Invalid argument to verify account: tatcli user verify --help\n") + } + }, +} + +func userVerify(username, tokenVerify string) { + verifyJSON, err := internal.Client().UserVerify(username, tokenVerify) + internal.Check(err) + + // Display return to user (contains clear password) + internal.Print(verifyJSON) + + if save && verifyJSON.Password != "" && verifyJSON.Username != "" && verifyJSON.URL != "" { + verifyJSON.Message = "" + jsonStr, err := json.MarshalIndent(verifyJSON, "", " ") + internal.Check(err) + jsonStr = append(jsonStr, '\n') + filename := internal.ConfigFile + dir := path.Dir(filename) + if _, err := os.Stat(dir); os.IsNotExist(err) { + internal.Check(os.Mkdir(dir, 0740)) + } + internal.Check(ioutil.WriteFile(filename, jsonStr, 0600)) + } +} diff --git a/tatcli/version/version.go b/tatcli/version/version.go new file mode 100644 index 0000000..ac06c5b --- /dev/null +++ b/tatcli/version/version.go @@ -0,0 +1,41 @@ +package version + +import ( + "fmt" + + "github.com/spf13/cobra" + "github.com/spf13/viper" + + "github.com/ovh/tat" + "github.com/ovh/tat/tatcli/internal" +) + +var versionNewLine bool + +func init() { + Cmd.Flags().BoolVarP(&versionNewLine, "versionNewLine", "", true, "New line after version number. If true, display Version Engine too") +} + +// Cmd version +var Cmd = &cobra.Command{ + Use: "version", + Short: "Display Version of tatcli and tat engine if configured: tatcli version", + Long: `tatcli version`, + Aliases: []string{"v"}, + Run: func(cmd *cobra.Command, args []string) { + if versionNewLine { + fmt.Printf("Version tatcli: %s\n", tat.Version) + + internal.ReadConfig() + if viper.GetString("url") == "" { + internal.Exit("Version Engine: No Engine Configured. See tatcli config --help\n") + } else { + out, err := internal.Client().Version() + internal.Check(err) + internal.Print(out) + } + } else { + fmt.Print(tat.Version) + } + }, +} diff --git a/types.go b/types.go index 52a4d9f..ab62c54 100644 --- a/types.go +++ b/types.go @@ -1,9 +1,9 @@ package tat -// Version of Tat Engine +// Version of Tat // One Line for this, used by release.sh script // Keep "const Version on one line" -const Version = "3.1.0" +const Version = "5.0.0" const ( // TatHeaderUsername is Tat_username header diff --git a/vendor/github.com/Shopify/sarama/CHANGELOG.md b/vendor/github.com/Shopify/sarama/CHANGELOG.md index 49ff921..aad986f 100644 --- a/vendor/github.com/Shopify/sarama/CHANGELOG.md +++ b/vendor/github.com/Shopify/sarama/CHANGELOG.md @@ -1,5 +1,32 @@ # Changelog +#### Version 1.11.0 (2016-12-20) + +New Features: + - Metrics! Thanks to Sébastien Launay for all his work on this feature + ([#701](https://github.com/Shopify/sarama/pull/701), + [#746](https://github.com/Shopify/sarama/pull/746), + [#766](https://github.com/Shopify/sarama/pull/766)). + - Add support for LZ4 compression + ([#786](https://github.com/Shopify/sarama/pull/786)). + - Add support for ListOffsetRequest v1 and Kafka 0.10.1 + ([#775](https://github.com/Shopify/sarama/pull/775)). + - Added a `HighWaterMarks` method to the Consumer which aggregates the + `HighWaterMarkOffset` values of its child topic/partitions + ([#769](https://github.com/Shopify/sarama/pull/769)). + +Bug Fixes: + - Fixed producing when using timestamps, compression and Kafka 0.10 + ([#759](https://github.com/Shopify/sarama/pull/759)). + - Added missing decoder methods to DescribeGroups response + ([#756](https://github.com/Shopify/sarama/pull/756)). + - Fix producer shutdown when `Return.Errors` is disabled + ([#787](https://github.com/Shopify/sarama/pull/787)). + - Don't mutate configuration in SyncProducer + ([#790](https://github.com/Shopify/sarama/pull/790)). + - Fix crash on SASL initialization failure + ([#795](https://github.com/Shopify/sarama/pull/795)). + #### Version 1.10.1 (2016-08-30) Bug Fixes: diff --git a/vendor/github.com/Shopify/sarama/consumer.go b/vendor/github.com/Shopify/sarama/consumer.go index 696b842..ddac564 100644 --- a/vendor/github.com/Shopify/sarama/consumer.go +++ b/vendor/github.com/Shopify/sarama/consumer.go @@ -63,8 +63,8 @@ type Consumer interface { // or OffsetOldest ConsumePartition(topic string, partition int32, offset int64) (PartitionConsumer, error) - // HighWaterMarks returns the current high water marks for each topic and partition - // Consistency between partitions is not garanteed since high water marks are updated separately. + // HighWaterMarks returns the current high water marks for each topic and partition. + // Consistency between partitions is not guaranteed since high water marks are updated separately. HighWaterMarks() map[string]map[int32]int64 // Close shuts down the consumer. It must be called after all child diff --git a/vendor/github.com/Shopify/sarama/produce_request.go b/vendor/github.com/Shopify/sarama/produce_request.go index b61a812..40dc801 100644 --- a/vendor/github.com/Shopify/sarama/produce_request.go +++ b/vendor/github.com/Shopify/sarama/produce_request.go @@ -14,7 +14,9 @@ const ( NoResponse RequiredAcks = 0 // WaitForLocal waits for only the local commit to succeed before responding. WaitForLocal RequiredAcks = 1 - // WaitForAll waits for all replicas to commit before responding. + // WaitForAll waits for all in-sync replicas to commit before responding. + // The minimum number of in-sync replicas is configured on the broker via + // the `min.insync.replicas` configuration key. WaitForAll RequiredAcks = -1 ) diff --git a/vendor/github.com/Sirupsen/logrus/README.md b/vendor/github.com/Sirupsen/logrus/README.md index 05d678a..206c746 100644 --- a/vendor/github.com/Sirupsen/logrus/README.md +++ b/vendor/github.com/Sirupsen/logrus/README.md @@ -87,8 +87,8 @@ func init() { // Log as JSON instead of the default ASCII formatter. log.SetFormatter(&log.JSONFormatter{}) - // Output to stderr instead of stdout, could also be a file. - log.SetOutput(os.Stderr) + // Output to stdout instead of the default stderr, could also be a file. + log.SetOutput(os.Stdout) // Only log the warning severity or above. log.SetLevel(log.WarnLevel) @@ -240,6 +240,7 @@ Note: Syslog hook also support connecting to local syslog (Ex. "/dev/log" or "/v | [Logmatic.io](https://github.com/logmatic/logmatic-go) | Hook for logging to [Logmatic.io](http://logmatic.io/) | | [Pushover](https://github.com/toorop/logrus_pushover) | Send error via [Pushover](https://pushover.net) | | [PostgreSQL](https://github.com/gemnasium/logrus-postgresql-hook) | Send logs to [PostgreSQL](http://postgresql.org) | +| [Logentrus](https://github.com/puddingfactory/logentrus) | Hook for logging to [Logentries](https://logentries.com/) | #### Level logging diff --git a/vendor/github.com/Sirupsen/logrus/text_formatter.go b/vendor/github.com/Sirupsen/logrus/text_formatter.go index 9114b3c..076de5d 100644 --- a/vendor/github.com/Sirupsen/logrus/text_formatter.go +++ b/vendor/github.com/Sirupsen/logrus/text_formatter.go @@ -28,10 +28,6 @@ func init() { isTerminal = IsTerminal() } -func miniTS() int { - return int(time.Since(baseTimestamp) / time.Second) -} - type TextFormatter struct { // Set to true to bypass checking for a TTY before outputting colors. ForceColors bool @@ -58,7 +54,7 @@ type TextFormatter struct { func (f *TextFormatter) Format(entry *Entry) ([]byte, error) { var b *bytes.Buffer - var keys []string = make([]string, 0, len(entry.Data)) + keys := make([]string, 0, len(entry.Data)) for k := range entry.Data { keys = append(keys, k) } @@ -115,8 +111,10 @@ func (f *TextFormatter) printColored(b *bytes.Buffer, entry *Entry, keys []strin levelText := strings.ToUpper(entry.Level.String())[0:4] - if !f.FullTimestamp { - fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%04d] %-44s ", levelColor, levelText, miniTS(), entry.Message) + if f.DisableTimestamp { + fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m %-44s ", levelColor, levelText, entry.Message) + } else if !f.FullTimestamp { + fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%04d] %-44s ", levelColor, levelText, int(entry.Time.Sub(baseTimestamp)/time.Second), entry.Message) } else { fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%s] %-44s ", levelColor, levelText, entry.Time.Format(timestampFormat), entry.Message) } diff --git a/vendor/github.com/yesnault/hashtag/LICENSE b/vendor/github.com/briandowns/spinner/LICENSE similarity index 89% rename from vendor/github.com/yesnault/hashtag/LICENSE rename to vendor/github.com/briandowns/spinner/LICENSE index e06d208..dd5b3a5 100644 --- a/vendor/github.com/yesnault/hashtag/LICENSE +++ b/vendor/github.com/briandowns/spinner/LICENSE @@ -1,4 +1,4 @@ -Apache License + Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ @@ -172,31 +172,3 @@ Apache License 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. - diff --git a/vendor/github.com/briandowns/spinner/README.md b/vendor/github.com/briandowns/spinner/README.md new file mode 100644 index 0000000..2b6df03 --- /dev/null +++ b/vendor/github.com/briandowns/spinner/README.md @@ -0,0 +1,194 @@ +# Spinner + +[![GoDoc](https://godoc.org/github.com/briandowns/spinner?status.svg)](https://godoc.org/github.com/briandowns/spinner) [![Build Status](https://travis-ci.org/briandowns/spinner.svg?branch=master)](https://travis-ci.org/briandowns/spinner) + +spinner is a simple package to add a spinner / progress indicator to any terminal application. Examples can be found below as well as full examples in the examples directory. + +For more detail about the library and its features, reference your local godoc once installed. + +Contributions welcome! + +## Installation + +```bash +go get github.com/briandowns/spinner +``` + +## Available Character Sets +(Numbered by their slice index) + +* 0. ```←↖↑↗→↘↓↙``` +* 1. ```▁▃▄▅▆▇█▇▆▅▄▃▁``` +* 2. ```▖▘▝▗``` +* 3. ```┤┘┴└├┌┬┐``` +* 4. ```◢◣◤◥``` +* 5. ```◰◳◲◱``` +* 6. ```◴◷◶◵``` +* 7. ```◐◓◑◒``` +* 8. ```.oO@*``` +* 9. ```|/-\``` +* 10. ```◡◡⊙⊙◠◠``` +* 11. ```⣾⣽⣻⢿⡿⣟⣯⣷``` +* 12. ```>))'> >))'> >))'> >))'> >))'> <'((< <'((< <'((<``` +* 13. ```⠁⠂⠄⡀⢀⠠⠐⠈``` +* 14. ```⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏``` +* 15. ```abcdefghijklmnopqrstuvwxyz``` +* 16. ```▉▊▋▌▍▎▏▎▍▌▋▊▉``` +* 17. ```■□▪▫``` +* 18. ```←↑→↓``` +* 19. ```╫╪``` +* 20. ```⇐⇖⇑⇗⇒⇘⇓⇙``` +* 21. ```⠁⠁⠉⠙⠚⠒⠂⠂⠒⠲⠴⠤⠄⠄⠤⠠⠠⠤⠦⠖⠒⠐⠐⠒⠓⠋⠉⠈⠈``` +* 22. ```⠈⠉⠋⠓⠒⠐⠐⠒⠖⠦⠤⠠⠠⠤⠦⠖⠒⠐⠐⠒⠓⠋⠉⠈``` +* 23. ```⠁⠉⠙⠚⠒⠂⠂⠒⠲⠴⠤⠄⠄⠤⠴⠲⠒⠂⠂⠒⠚⠙⠉⠁``` +* 24. ```⠋⠙⠚⠒⠂⠂⠒⠲⠴⠦⠖⠒⠐⠐⠒⠓⠋``` +* 25. ```ヲァィゥェォャュョッアイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワン``` +* 26. ```. .. ...``` +* 27. ```▁▂▃▄▅▆▇█▉▊▋▌▍▎▏▏▎▍▌▋▊▉█▇▆▅▄▃▂▁``` +* 28. ```.oO°Oo.``` +* 29. ```+x``` +* 30. ```v<^>``` +* 31. ```>>---> >>---> >>---> >>---> >>---> <---<< <---<< <---<< <---<< <---<<``` +* 32. ```| || ||| |||| ||||| |||||| ||||| |||| ||| || |``` +* 33. ```[] [=] [==] [===] [====] [=====] [======] [=======] [========] [=========] [==========]``` +* 34. ```(*---------) (-*--------) (--*-------) (---*------) (----*-----) (-----*----) (------*---) (-------*--) (--------*-) (---------*)``` +* 35. ```█▒▒▒▒▒▒▒▒▒ ███▒▒▒▒▒▒▒ █████▒▒▒▒▒ ███████▒▒▒ ██████████``` +* 36 ```[ ] [=> ] [===> ] [=====> ] [======> ] [========> ] [==========> ] [============> ] [==============> ] [================> ] [==================> ] [===================>]``` + +## Features + +* Start +* Stop +* Restart +* Reverse direction +* Update the spinner character set +* Update the spinner speed +* Prefix or append text +* Change spinner color +* Get spinner status +* Chain, pipe, redirect output +* Output final string on spinner/indicator completion + +## Examples + +```Go +package main + +import ( + "github.com/briandowns/spinner" + "time" +) + +func main() { + s := spinner.New(spinner.CharSets[9], 100*time.Millisecond) // Build our new spinner + s.Start() // Start the spinner + time.Sleep(4 * time.Second) // Run for some time to simulate work + s.Stop() +} +``` + +## Update the character set and restart the spinner + +```Go +s.UpdateCharSet(spinner.CharSets[1]) // Update spinner to use a different character set +s.Restart() // Restart the spinner +time.Sleep(4 * time.Second) +s.Stop() +``` + +## Update spin speed and restart the spinner + +```Go +s.UpdateSpeed(200 * time.Millisecond) // Update the speed the spinner spins at +s.Restart() +time.Sleep(4 * time.Second) +s.Stop() +``` + +## Reverse the direction of the spinner + +```Go +s.Reverse() // Reverse the direction the spinner is spinning +s.Restart() +time.Sleep(4 * time.Second) +s.Stop() +``` + +## Provide your own spinner + +(or send me an issue or pull request to add to the project) + +```Go +someSet := []string{"+", "-"} +s := spinner.New(someSet, 100*time.Millisecond) +``` + +## Prefix or append text to the spinner + +```Go +s.Prefix = "prefixed text: " // Prefix text before the spinner +s.Suffix = " :appended text" // Append text after the spinner +``` + +## Set or change the color of the spinner. Default color is white. This will restart the spinner with the new color. + +```Go +s.Color("red") // Set the spinner color to red +``` + +## Generate a sequence of numbers + +```Go +setOfDigits := spinner.GenerateNumberSequence(25) // Generate a 25 digit string of numbers +s := spinner.New(setOfDigits, 100*time.Millisecond) +``` + +## Get spinner status + +```Go +fmt.Println(s.ST) +``` + +## Unix pipe and redirect + +Feature suggested and write up by [dekz](https://github.com/dekz) + +Setting the Spinner Writer to Stderr helps show progress to the user, with the enhancement to chain, pipe or redirect the output. + +```go +s := spinner.New(spinner.CharSets[11], 100*time.Millisecond) +s.Suffix = " Encrypting data..." +s.Writer = os.Stderr +s.Start() +// Encrypt the data into ciphertext +fmt.Println(os.Stdout, ciphertext) +``` + +```sh +> myprog encrypt "Secret text" > encrypted.txt +⣯ Encrypting data... +``` + +```sh +> cat encrypted.txt +1243hjkbas23i9ah27sj39jghv237n2oa93hg83 +``` + +## Final String Output + +Add additional output when the spinner/indicator has completed. The "final" output string can be multi-lined and will be written to wherever the `io.Writer` has been configured for. + +```Go +s := spinner.New(spinner.CharSets[9], 100*time.Millisecond) +s.FinalMSG = "Complete!\nNew line!\nAnother one!\n" +s.Start() +time.Sleep(4 * time.Second) +s.Stop() +``` + +Output +```sh +Complete! +New line! +Another one! +``` \ No newline at end of file diff --git a/vendor/github.com/briandowns/spinner/character_sets.go b/vendor/github.com/briandowns/spinner/character_sets.go new file mode 100644 index 0000000..bd1b5cb --- /dev/null +++ b/vendor/github.com/briandowns/spinner/character_sets.go @@ -0,0 +1,42 @@ +package spinner + +// CharSets contains the available character sets +var CharSets = map[int][]string{ + 0: {"←", "↖", "↑", "↗", "→", "↘", "↓", "↙"}, + 1: {"▁", "▃", "▄", "▅", "▆", "▇", "█", "▇", "▆", "▅", "▄", "▃", "▁"}, + 2: {"▖", "▘", "▝", "▗"}, + 3: {"┤", "┘", "┴", "└", "├", "┌", "┬", "┐"}, + 4: {"◢", "◣", "◤", "◥"}, + 5: {"◰", "◳", "◲", "◱"}, + 6: {"◴", "◷", "◶", "◵"}, + 7: {"◐", "◓", "◑", "◒"}, + 8: {".", "o", "O", "@", "*"}, + 9: {"|", "/", "-", "\\"}, + 10: {"◡◡", "⊙⊙", "◠◠"}, + 11: {"⣾", "⣽", "⣻", "⢿", "⡿", "⣟", "⣯", "⣷"}, + 12: {">))'>", " >))'>", " >))'>", " >))'>", " >))'>", " <'((<", " <'((<", " <'((<"}, + 13: {"⠁", "⠂", "⠄", "⡀", "⢀", "⠠", "⠐", "⠈"}, + 14: {"⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"}, + 15: {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"}, + 16: {"▉", "▊", "▋", "▌", "▍", "▎", "▏", "▎", "▍", "▌", "▋", "▊", "▉"}, + 17: {"■", "□", "▪", "▫"}, + 18: {"←", "↑", "→", "↓"}, + 19: {"╫", "╪"}, + 20: {"⇐", "⇖", "⇑", "⇗", "⇒", "⇘", "⇓", "⇙"}, + 21: {"⠁", "⠁", "⠉", "⠙", "⠚", "⠒", "⠂", "⠂", "⠒", "⠲", "⠴", "⠤", "⠄", "⠄", "⠤", "⠠", "⠠", "⠤", "⠦", "⠖", "⠒", "⠐", "⠐", "⠒", "⠓", "⠋", "⠉", "⠈", "⠈"}, + 22: {"⠈", "⠉", "⠋", "⠓", "⠒", "⠐", "⠐", "⠒", "⠖", "⠦", "⠤", "⠠", "⠠", "⠤", "⠦", "⠖", "⠒", "⠐", "⠐", "⠒", "⠓", "⠋", "⠉", "⠈"}, + 23: {"⠁", "⠉", "⠙", "⠚", "⠒", "⠂", "⠂", "⠒", "⠲", "⠴", "⠤", "⠄", "⠄", "⠤", "⠴", "⠲", "⠒", "⠂", "⠂", "⠒", "⠚", "⠙", "⠉", "⠁"}, + 24: {"⠋", "⠙", "⠚", "⠒", "⠂", "⠂", "⠒", "⠲", "⠴", "⠦", "⠖", "⠒", "⠐", "⠐", "⠒", "⠓", "⠋"}, + 25: {"ヲ", "ァ", "ィ", "ゥ", "ェ", "ォ", "ャ", "ュ", "ョ", "ッ", "ア", "イ", "ウ", "エ", "オ", "カ", "キ", "ク", "ケ", "コ", "サ", "シ", "ス", "セ", "ソ", "タ", "チ", "ツ", "テ", "ト", "ナ", "ニ", "ヌ", "ネ", "ノ", "ハ", "ヒ", "フ", "ヘ", "ホ", "マ", "ミ", "ム", "メ", "モ", "ヤ", "ユ", "ヨ", "ラ", "リ", "ル", "レ", "ロ", "ワ", "ン"}, + 26: {".", "..", "..."}, + 27: {"▁", "▂", "▃", "▄", "▅", "▆", "▇", "█", "▉", "▊", "▋", "▌", "▍", "▎", "▏", "▏", "▎", "▍", "▌", "▋", "▊", "▉", "█", "▇", "▆", "▅", "▄", "▃", "▂", "▁"}, + 28: {".", "o", "O", "°", "O", "o", "."}, + 29: {"+", "x"}, + 30: {"v", "<", "^", ">"}, + 31: {">>--->", " >>--->", " >>--->", " >>--->", " >>--->", " <---<<", " <---<<", " <---<<", " <---<<", "<---<<"}, + 32: {"|", "||", "|||", "||||", "|||||", "|||||||", "||||||||", "|||||||", "||||||", "|||||", "||||", "|||", "||", "|"}, + 33: {"[ ]", "[= ]", "[== ]", "[=== ]", "[==== ]", "[===== ]", "[====== ]", "[======= ]", "[======== ]", "[========= ]", "[==========]"}, + 34: {"(*---------)", "(-*--------)", "(--*-------)", "(---*------)", "(----*-----)", "(-----*----)", "(------*---)", "(-------*--)", "(--------*-)", "(---------*)"}, + 35: {"█▒▒▒▒▒▒▒▒▒", "███▒▒▒▒▒▒▒", "█████▒▒▒▒▒", "███████▒▒▒", "██████████"}, + 36: {"[ ]", "[=> ]", "[===> ]", "[=====> ]", "[======> ]", "[========> ]", "[==========> ]", "[============> ]", "[==============> ]", "[================> ]", "[==================> ]", "[===================>]"}, +} diff --git a/vendor/github.com/briandowns/spinner/spinner.go b/vendor/github.com/briandowns/spinner/spinner.go new file mode 100644 index 0000000..29b9c08 --- /dev/null +++ b/vendor/github.com/briandowns/spinner/spinner.go @@ -0,0 +1,198 @@ +// 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 spinner is a simple package to add a spinner / progress indicator to any terminal application. +package spinner + +import ( + "errors" + "fmt" + "io" + "strconv" + "sync" + "time" + "unicode/utf8" + + "github.com/fatih/color" +) + +// errInvalidColor is returned when attempting to set an invalid color +var errInvalidColor = errors.New("invalid color") + +// validColors holds an array of the only colors allowed +var validColors = []string{"red", "green", "yellow", "blue", "magenta", "cyan", "white"} + +// validColor will make sure the given color is actually allowed +func validColor(c string) bool { + for _, i := range validColors { + if c == i { + return true + } + } + return false +} + +// Spinner struct to hold the provided options +type Spinner struct { + Delay time.Duration // Delay is the speed of the indicator + chars []string // chars holds the chosen character set + Prefix string // Prefix is the text preppended to the indicator + Suffix string // Suffix is the text appended to the indicator + FinalMSG string // string displayed after Stop() is called + lastOutput string // last character(set) written + color func(a ...interface{}) string // default color is white + lock *sync.RWMutex // + Writer io.Writer // to make testing better, exported so users have access + active bool // active holds the state of the spinner + stopChan chan struct{} // stopChan is a channel used to stop the indicator +} + +// New provides a pointer to an instance of Spinner with the supplied options +func New(cs []string, d time.Duration) *Spinner { + return &Spinner{ + Delay: d, + chars: cs, + color: color.New(color.FgWhite).SprintFunc(), + lock: &sync.RWMutex{}, + Writer: color.Output, + active: false, + stopChan: make(chan struct{}, 1), + } +} + +// Start will start the indicator +func (s *Spinner) Start() { + if s.active { + return + } + s.active = true + + go func() { + for { + for i := 0; i < len(s.chars); i++ { + select { + case <-s.stopChan: + return + default: + s.lock.Lock() + s.erase() + outColor := fmt.Sprintf("%s%s%s ", s.Prefix, s.color(s.chars[i]), s.Suffix) + outPlain := fmt.Sprintf("%s%s%s ", s.Prefix, s.chars[i], s.Suffix) + fmt.Fprint(s.Writer, outColor) + s.lastOutput = outPlain + delay := s.Delay + s.lock.Unlock() + + time.Sleep(delay) + } + } + } + }() +} + +// Stop stops the indicator +func (s *Spinner) Stop() { + s.lock.Lock() + defer s.lock.Unlock() + if s.active { + s.active = false + s.erase() + if s.FinalMSG != "" { + fmt.Fprintf(s.Writer, s.FinalMSG) + } + s.stopChan <- struct{}{} + } +} + +// Restart will stop and start the indicator +func (s *Spinner) Restart() { + s.Stop() + s.Start() +} + +// Reverse will reverse the order of the slice assigned to the indicator +func (s *Spinner) Reverse() { + s.lock.Lock() + defer s.lock.Unlock() + for i, j := 0, len(s.chars)-1; i < j; i, j = i+1, j-1 { + s.chars[i], s.chars[j] = s.chars[j], s.chars[i] + } +} + +// Color will set the struct field for the given color to be used +func (s *Spinner) Color(c string) error { + if validColor(c) { + switch c { + case "red": + s.color = color.New(color.FgRed).SprintFunc() + s.Restart() + case "yellow": + s.color = color.New(color.FgYellow).SprintFunc() + s.Restart() + case "green": + s.color = color.New(color.FgGreen).SprintFunc() + s.Restart() + case "magenta": + s.color = color.New(color.FgMagenta).SprintFunc() + s.Restart() + case "blue": + s.color = color.New(color.FgBlue).SprintFunc() + s.Restart() + case "cyan": + s.color = color.New(color.FgCyan).SprintFunc() + s.Restart() + case "white": + s.color = color.New(color.FgWhite).SprintFunc() + s.Restart() + default: + return errInvalidColor + } + } + return nil +} + +// UpdateSpeed will set the indicator delay to the given value +func (s *Spinner) UpdateSpeed(d time.Duration) { + s.lock.Lock() + defer s.lock.Unlock() + s.Delay = d +} + +// UpdateCharSet will change the current character set to the given one +func (s *Spinner) UpdateCharSet(cs []string) { + s.lock.Lock() + defer s.lock.Unlock() + s.chars = cs +} + +// erase deletes written characters +// +// Caller must already hold s.lock. +func (s *Spinner) erase() { + n := utf8.RuneCountInString(s.lastOutput) + for _, c := range []string{"\b", " ", "\b"} { + for i := 0; i < n; i++ { + fmt.Fprintf(s.Writer, c) + } + } + s.lastOutput = "" +} + +// GenerateNumberSequence will generate a slice of integers at the +// provided length and convert them each to a string +func GenerateNumberSequence(length int) []string { + numSeq := make([]string, length) + for i := 0; i < length; i++ { + numSeq[i] = strconv.Itoa(i) + } + return numSeq +} diff --git a/vendor/github.com/eapache/go-resiliency/retrier/README.md b/vendor/github.com/eapache/go-resiliency/retrier/README.md deleted file mode 100644 index dd30af7..0000000 --- a/vendor/github.com/eapache/go-resiliency/retrier/README.md +++ /dev/null @@ -1,26 +0,0 @@ -retrier -======= - -[![Build Status](https://travis-ci.org/eapache/go-resiliency.svg?branch=master)](https://travis-ci.org/eapache/go-resiliency) -[![GoDoc](https://godoc.org/github.com/eapache/go-resiliency/retrier?status.svg)](https://godoc.org/github.com/eapache/go-resiliency/retrier) -[![Code of Conduct](https://img.shields.io/badge/code%20of%20conduct-active-blue.svg)](https://eapache.github.io/conduct.html) - -The retriable resiliency pattern for golang. - -Creating a retrier takes two parameters: -- the times to back-off between retries (and implicitly the number of times to - retry) -- the classifier that determines which errors to retry - -```go -r := retrier.New(retrier.ConstantBackoff(3, 100*time.Millisecond), nil) - -err := r.Run(func() error { - // do some work - return nil -}) - -if err != nil { - // handle the case where the work failed three times -} -``` diff --git a/vendor/github.com/eapache/go-resiliency/retrier/backoffs.go b/vendor/github.com/eapache/go-resiliency/retrier/backoffs.go deleted file mode 100644 index faf6f8c..0000000 --- a/vendor/github.com/eapache/go-resiliency/retrier/backoffs.go +++ /dev/null @@ -1,24 +0,0 @@ -package retrier - -import "time" - -// ConstantBackoff generates a simple back-off strategy of retrying 'n' times, and waiting 'amount' time after each one. -func ConstantBackoff(n int, amount time.Duration) []time.Duration { - ret := make([]time.Duration, n) - for i := range ret { - ret[i] = amount - } - return ret -} - -// ExponentialBackoff generates a simple back-off strategy of retrying 'n' times, and doubling the amount of -// time waited after each one. -func ExponentialBackoff(n int, initialAmount time.Duration) []time.Duration { - ret := make([]time.Duration, n) - next := initialAmount - for i := range ret { - ret[i] = next - next *= 2 - } - return ret -} diff --git a/vendor/github.com/eapache/go-resiliency/retrier/classifier.go b/vendor/github.com/eapache/go-resiliency/retrier/classifier.go deleted file mode 100644 index 7dd71c7..0000000 --- a/vendor/github.com/eapache/go-resiliency/retrier/classifier.go +++ /dev/null @@ -1,66 +0,0 @@ -package retrier - -// Action is the type returned by a Classifier to indicate how the Retrier should proceed. -type Action int - -const ( - Succeed Action = iota // Succeed indicates the Retrier should treat this value as a success. - Fail // Fail indicates the Retrier should treat this value as a hard failure and not retry. - Retry // Retry indicates the Retrier should treat this value as a soft failure and retry. -) - -// Classifier is the interface implemented by anything that can classify Errors for a Retrier. -type Classifier interface { - Classify(error) Action -} - -// DefaultClassifier classifies errors in the simplest way possible. If -// the error is nil, it returns Succeed, otherwise it returns Retry. -type DefaultClassifier struct{} - -// Classify implements the Classifier interface. -func (c DefaultClassifier) Classify(err error) Action { - if err == nil { - return Succeed - } - - return Retry -} - -// WhitelistClassifier classifies errors based on a whitelist. If the error is nil, it -// returns Succeed; if the error is in the whitelist, it returns Retry; otherwise, it returns Fail. -type WhitelistClassifier []error - -// Classify implements the Classifier interface. -func (list WhitelistClassifier) Classify(err error) Action { - if err == nil { - return Succeed - } - - for _, pass := range list { - if err == pass { - return Retry - } - } - - return Fail -} - -// BlacklistClassifier classifies errors based on a blacklist. If the error is nil, it -// returns Succeed; if the error is in the blacklist, it returns Fail; otherwise, it returns Retry. -type BlacklistClassifier []error - -// Classify implements the Classifier interface. -func (list BlacklistClassifier) Classify(err error) Action { - if err == nil { - return Succeed - } - - for _, pass := range list { - if err == pass { - return Fail - } - } - - return Retry -} diff --git a/vendor/github.com/eapache/go-resiliency/retrier/retrier.go b/vendor/github.com/eapache/go-resiliency/retrier/retrier.go deleted file mode 100644 index ff32874..0000000 --- a/vendor/github.com/eapache/go-resiliency/retrier/retrier.go +++ /dev/null @@ -1,69 +0,0 @@ -// Package retrier implements the "retriable" resiliency pattern for Go. -package retrier - -import ( - "math/rand" - "time" -) - -// Retrier implements the "retriable" resiliency pattern, abstracting out the process of retrying a failed action -// a certain number of times with an optional back-off between each retry. -type Retrier struct { - backoff []time.Duration - class Classifier - jitter float64 - rand *rand.Rand -} - -// New constructs a Retrier with the given backoff pattern and classifier. The length of the backoff pattern -// indicates how many times an action will be retried, and the value at each index indicates the amount of time -// waited before each subsequent retry. The classifier is used to determine which errors should be retried and -// which should cause the retrier to fail fast. The DefaultClassifier is used if nil is passed. -func New(backoff []time.Duration, class Classifier) *Retrier { - if class == nil { - class = DefaultClassifier{} - } - - return &Retrier{ - backoff: backoff, - class: class, - rand: rand.New(rand.NewSource(time.Now().UnixNano())), - } -} - -// Run executes the given work function, then classifies its return value based on the classifier used -// to construct the Retrier. If the result is Succeed or Fail, the return value of the work function is -// returned to the caller. If the result is Retry, then Run sleeps according to the its backoff policy -// before retrying. If the total number of retries is exceeded then the return value of the work function -// is returned to the caller regardless. -func (r *Retrier) Run(work func() error) error { - retries := 0 - for { - ret := work() - - switch r.class.Classify(ret) { - case Succeed, Fail: - return ret - case Retry: - if retries >= len(r.backoff) { - return ret - } - time.Sleep(r.calcSleep(retries)) - retries++ - } - } -} - -func (r *Retrier) calcSleep(i int) time.Duration { - // take a random float in the range (-r.jitter, +r.jitter) and multiply it by the base amount - return r.backoff[i] + time.Duration(((r.rand.Float64()*2)-1)*r.jitter*float64(r.backoff[i])) -} - -// SetJitter sets the amount of jitter on each back-off to a factor between 0.0 and 1.0 (values outside this range -// are silently ignored). When a retry occurs, the back-off is adjusted by a random amount up to this value. -func (r *Retrier) SetJitter(jit float64) { - if jit < 0 || jit > 1 { - return - } - r.jitter = jit -} diff --git a/vendor/github.com/fatih/color/LICENSE.md b/vendor/github.com/fatih/color/LICENSE.md new file mode 100644 index 0000000..25fdaf6 --- /dev/null +++ b/vendor/github.com/fatih/color/LICENSE.md @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2013 Fatih Arslan + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/github.com/fatih/color/README.md b/vendor/github.com/fatih/color/README.md new file mode 100644 index 0000000..7c8eea2 --- /dev/null +++ b/vendor/github.com/fatih/color/README.md @@ -0,0 +1,175 @@ +# Color [![GoDoc](http://img.shields.io/badge/go-documentation-blue.svg?style=flat-square)](http://godoc.org/github.com/fatih/color) [![Build Status](http://img.shields.io/travis/fatih/color.svg?style=flat-square)](https://travis-ci.org/fatih/color) + + + +Color lets you use colorized outputs in terms of [ANSI Escape +Codes](http://en.wikipedia.org/wiki/ANSI_escape_code#Colors) in Go (Golang). It +has support for Windows too! The API can be used in several ways, pick one that +suits you. + + + +![Color](http://i.imgur.com/c1JI0lA.png) + + +## Install + +```bash +go get github.com/fatih/color +``` + +## Examples + +### Standard colors + +```go +// Print with default helper functions +color.Cyan("Prints text in cyan.") + +// A newline will be appended automatically +color.Blue("Prints %s in blue.", "text") + +// These are using the default foreground colors +color.Red("We have red") +color.Magenta("And many others ..") + +``` + +### Mix and reuse colors + +```go +// Create a new color object +c := color.New(color.FgCyan).Add(color.Underline) +c.Println("Prints cyan text with an underline.") + +// Or just add them to New() +d := color.New(color.FgCyan, color.Bold) +d.Printf("This prints bold cyan %s\n", "too!.") + +// Mix up foreground and background colors, create new mixes! +red := color.New(color.FgRed) + +boldRed := red.Add(color.Bold) +boldRed.Println("This will print text in bold red.") + +whiteBackground := red.Add(color.BgWhite) +whiteBackground.Println("Red text with white background.") +``` + +### Use your own output (io.Writer) + +```go +// Use your own io.Writer output +color.New(color.FgBlue).Fprintln(myWriter, "blue color!") + +blue := color.New(color.FgBlue) +blue.Fprint(writer, "This will print text in blue.") +``` + +### Custom print functions (PrintFunc) + +```go +// Create a custom print function for convenience +red := color.New(color.FgRed).PrintfFunc() +red("Warning") +red("Error: %s", err) + +// Mix up multiple attributes +notice := color.New(color.Bold, color.FgGreen).PrintlnFunc() +notice("Don't forget this...") +``` + +### Custom fprint functions (FprintFunc) + +```go +blue := color.New(FgBlue).FprintfFunc() +blue(myWriter, "important notice: %s", stars) + +// Mix up with multiple attributes +success := color.New(color.Bold, color.FgGreen).FprintlnFunc() +success(myWriter, don't forget this...") +``` + +### Insert into noncolor strings (SprintFunc) + +```go +// Create SprintXxx functions to mix strings with other non-colorized strings: +yellow := color.New(color.FgYellow).SprintFunc() +red := color.New(color.FgRed).SprintFunc() +fmt.Printf("This is a %s and this is %s.\n", yellow("warning"), red("error")) + +info := color.New(color.FgWhite, color.BgGreen).SprintFunc() +fmt.Printf("This %s rocks!\n", info("package")) + +// Use helper functions +fmt.Println("This", color.RedString("warning"), "should be not neglected.") +fmt.Printf("%v %v\n", color.GreenString("Info:"), "an important message.") + +// Windows supported too! Just don't forget to change the output to color.Output +fmt.Fprintf(color.Output, "Windows support: %s", color.GreenString("PASS")) +``` + +### Plug into existing code + +```go +// Use handy standard colors +color.Set(color.FgYellow) + +fmt.Println("Existing text will now be in yellow") +fmt.Printf("This one %s\n", "too") + +color.Unset() // Don't forget to unset + +// You can mix up parameters +color.Set(color.FgMagenta, color.Bold) +defer color.Unset() // Use it in your function + +fmt.Println("All text will now be bold magenta.") +``` + +### Disable color + +There might be a case where you want to disable color output (for example to +pipe the standard output of your app to somewhere else). `Color` has support to +disable colors both globally and for single color definition. For example +suppose you have a CLI app and a `--no-color` bool flag. You can easily disable +the color output with: + +```go + +var flagNoColor = flag.Bool("no-color", false, "Disable color output") + +if *flagNoColor { + color.NoColor = true // disables colorized output +} +``` + +It also has support for single color definitions (local). You can +disable/enable color output on the fly: + +```go +c := color.New(color.FgCyan) +c.Println("Prints cyan text") + +c.DisableColor() +c.Println("This is printed without any color") + +c.EnableColor() +c.Println("This prints again cyan...") +``` + +## Todo + +* Save/Return previous values +* Evaluate fmt.Formatter interface + + +## Credits + + * [Fatih Arslan](https://github.com/fatih) + * Windows support via @mattn: [colorable](https://github.com/mattn/go-colorable) + +## License + +The MIT License (MIT) - see [`LICENSE.md`](https://github.com/fatih/color/blob/master/LICENSE.md) for more details + diff --git a/vendor/github.com/fatih/color/color.go b/vendor/github.com/fatih/color/color.go new file mode 100644 index 0000000..dba8f21 --- /dev/null +++ b/vendor/github.com/fatih/color/color.go @@ -0,0 +1,510 @@ +package color + +import ( + "fmt" + "io" + "os" + "strconv" + "strings" + "sync" + + "github.com/mattn/go-colorable" + "github.com/mattn/go-isatty" +) + +var ( + // NoColor defines if the output is colorized or not. It's dynamically set to + // false or true based on the stdout's file descriptor referring to a terminal + // or not. This is a global option and affects all colors. For more control + // over each color block use the methods DisableColor() individually. + NoColor = !isatty.IsTerminal(os.Stdout.Fd()) || os.Getenv("TERM") == "dumb" + + // Output defines the standard output of the print functions. By default + // os.Stdout is used. + Output = colorable.NewColorableStdout() + + // colorsCache is used to reduce the count of created Color objects and + // allows to reuse already created objects with required Attribute. + colorsCache = make(map[Attribute]*Color) + colorsCacheMu sync.Mutex // protects colorsCache +) + +// Color defines a custom color object which is defined by SGR parameters. +type Color struct { + params []Attribute + noColor *bool +} + +// Attribute defines a single SGR Code +type Attribute int + +const escape = "\x1b" + +// Base attributes +const ( + Reset Attribute = iota + Bold + Faint + Italic + Underline + BlinkSlow + BlinkRapid + ReverseVideo + Concealed + CrossedOut +) + +// Foreground text colors +const ( + FgBlack Attribute = iota + 30 + FgRed + FgGreen + FgYellow + FgBlue + FgMagenta + FgCyan + FgWhite +) + +// Foreground Hi-Intensity text colors +const ( + FgHiBlack Attribute = iota + 90 + FgHiRed + FgHiGreen + FgHiYellow + FgHiBlue + FgHiMagenta + FgHiCyan + FgHiWhite +) + +// Background text colors +const ( + BgBlack Attribute = iota + 40 + BgRed + BgGreen + BgYellow + BgBlue + BgMagenta + BgCyan + BgWhite +) + +// Background Hi-Intensity text colors +const ( + BgHiBlack Attribute = iota + 100 + BgHiRed + BgHiGreen + BgHiYellow + BgHiBlue + BgHiMagenta + BgHiCyan + BgHiWhite +) + +// New returns a newly created color object. +func New(value ...Attribute) *Color { + c := &Color{params: make([]Attribute, 0)} + c.Add(value...) + return c +} + +// Set sets the given parameters immediately. It will change the color of +// output with the given SGR parameters until color.Unset() is called. +func Set(p ...Attribute) *Color { + c := New(p...) + c.Set() + return c +} + +// Unset resets all escape attributes and clears the output. Usually should +// be called after Set(). +func Unset() { + if NoColor { + return + } + + fmt.Fprintf(Output, "%s[%dm", escape, Reset) +} + +// Set sets the SGR sequence. +func (c *Color) Set() *Color { + if c.isNoColorSet() { + return c + } + + fmt.Fprintf(Output, c.format()) + return c +} + +func (c *Color) unset() { + if c.isNoColorSet() { + return + } + + Unset() +} + +func (c *Color) setWriter(w io.Writer) *Color { + if c.isNoColorSet() { + return c + } + + fmt.Fprintf(w, c.format()) + return c +} + +func (c *Color) unsetWriter(w io.Writer) { + if c.isNoColorSet() { + return + } + + if NoColor { + return + } + + fmt.Fprintf(w, "%s[%dm", escape, Reset) +} + +// Add is used to chain SGR parameters. Use as many as parameters to combine +// and create custom color objects. Example: Add(color.FgRed, color.Underline). +func (c *Color) Add(value ...Attribute) *Color { + c.params = append(c.params, value...) + return c +} + +func (c *Color) prepend(value Attribute) { + c.params = append(c.params, 0) + copy(c.params[1:], c.params[0:]) + c.params[0] = value +} + +// Fprint formats using the default formats for its operands and writes to w. +// Spaces are added between operands when neither is a string. +// It returns the number of bytes written and any write error encountered. +// On Windows, users should wrap w with colorable.NewColorable() if w is of +// type *os.File. +func (c *Color) Fprint(w io.Writer, a ...interface{}) (n int, err error) { + c.setWriter(w) + defer c.unsetWriter(w) + + return fmt.Fprint(w, a...) +} + +// Print formats using the default formats for its operands and writes to +// standard output. Spaces are added between operands when neither is a +// string. It returns the number of bytes written and any write error +// encountered. This is the standard fmt.Print() method wrapped with the given +// color. +func (c *Color) Print(a ...interface{}) (n int, err error) { + c.Set() + defer c.unset() + + return fmt.Fprint(Output, a...) +} + +// Fprintf formats according to a format specifier and writes to w. +// It returns the number of bytes written and any write error encountered. +// On Windows, users should wrap w with colorable.NewColorable() if w is of +// type *os.File. +func (c *Color) Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error) { + c.setWriter(w) + defer c.unsetWriter(w) + + return fmt.Fprintf(w, format, a...) +} + +// Printf formats according to a format specifier and writes to standard output. +// It returns the number of bytes written and any write error encountered. +// This is the standard fmt.Printf() method wrapped with the given color. +func (c *Color) Printf(format string, a ...interface{}) (n int, err error) { + c.Set() + defer c.unset() + + return fmt.Fprintf(Output, format, a...) +} + +// Fprintln formats using the default formats for its operands and writes to w. +// Spaces are always added between operands and a newline is appended. +// On Windows, users should wrap w with colorable.NewColorable() if w is of +// type *os.File. +func (c *Color) Fprintln(w io.Writer, a ...interface{}) (n int, err error) { + c.setWriter(w) + defer c.unsetWriter(w) + + return fmt.Fprintln(w, a...) +} + +// Println formats using the default formats for its operands and writes to +// standard output. Spaces are always added between operands and a newline is +// appended. It returns the number of bytes written and any write error +// encountered. This is the standard fmt.Print() method wrapped with the given +// color. +func (c *Color) Println(a ...interface{}) (n int, err error) { + c.Set() + defer c.unset() + + return fmt.Fprintln(Output, a...) +} + +// FprintFunc returns a new function that prints the passed arguments as +// colorized with color.Fprint(). +func (c *Color) FprintFunc() func(w io.Writer, a ...interface{}) { + return func(w io.Writer, a ...interface{}) { + c.Fprint(w, a...) + } +} + +// PrintFunc returns a new function that prints the passed arguments as +// colorized with color.Print(). +func (c *Color) PrintFunc() func(a ...interface{}) { + return func(a ...interface{}) { + c.Print(a...) + } +} + +// FprintfFunc returns a new function that prints the passed arguments as +// colorized with color.Fprintf(). +func (c *Color) FprintfFunc() func(w io.Writer, format string, a ...interface{}) { + return func(w io.Writer, format string, a ...interface{}) { + c.Fprintf(w, format, a...) + } +} + +// PrintfFunc returns a new function that prints the passed arguments as +// colorized with color.Printf(). +func (c *Color) PrintfFunc() func(format string, a ...interface{}) { + return func(format string, a ...interface{}) { + c.Printf(format, a...) + } +} + +// FprintlnFunc returns a new function that prints the passed arguments as +// colorized with color.Fprintln(). +func (c *Color) FprintlnFunc() func(w io.Writer, a ...interface{}) { + return func(w io.Writer, a ...interface{}) { + c.Fprintln(w, a...) + } +} + +// PrintlnFunc returns a new function that prints the passed arguments as +// colorized with color.Println(). +func (c *Color) PrintlnFunc() func(a ...interface{}) { + return func(a ...interface{}) { + c.Println(a...) + } +} + +// SprintFunc returns a new function that returns colorized strings for the +// given arguments with fmt.Sprint(). Useful to put into or mix into other +// string. Windows users should use this in conjunction with color.Output, example: +// +// put := New(FgYellow).SprintFunc() +// fmt.Fprintf(color.Output, "This is a %s", put("warning")) +func (c *Color) SprintFunc() func(a ...interface{}) string { + return func(a ...interface{}) string { + return c.wrap(fmt.Sprint(a...)) + } +} + +// SprintfFunc returns a new function that returns colorized strings for the +// given arguments with fmt.Sprintf(). Useful to put into or mix into other +// string. Windows users should use this in conjunction with color.Output. +func (c *Color) SprintfFunc() func(format string, a ...interface{}) string { + return func(format string, a ...interface{}) string { + return c.wrap(fmt.Sprintf(format, a...)) + } +} + +// SprintlnFunc returns a new function that returns colorized strings for the +// given arguments with fmt.Sprintln(). Useful to put into or mix into other +// string. Windows users should use this in conjunction with color.Output. +func (c *Color) SprintlnFunc() func(a ...interface{}) string { + return func(a ...interface{}) string { + return c.wrap(fmt.Sprintln(a...)) + } +} + +// sequence returns a formated SGR sequence to be plugged into a "\x1b[...m" +// an example output might be: "1;36" -> bold cyan +func (c *Color) sequence() string { + format := make([]string, len(c.params)) + for i, v := range c.params { + format[i] = strconv.Itoa(int(v)) + } + + return strings.Join(format, ";") +} + +// wrap wraps the s string with the colors attributes. The string is ready to +// be printed. +func (c *Color) wrap(s string) string { + if c.isNoColorSet() { + return s + } + + return c.format() + s + c.unformat() +} + +func (c *Color) format() string { + return fmt.Sprintf("%s[%sm", escape, c.sequence()) +} + +func (c *Color) unformat() string { + return fmt.Sprintf("%s[%dm", escape, Reset) +} + +// DisableColor disables the color output. Useful to not change any existing +// code and still being able to output. Can be used for flags like +// "--no-color". To enable back use EnableColor() method. +func (c *Color) DisableColor() { + c.noColor = boolPtr(true) +} + +// EnableColor enables the color output. Use it in conjunction with +// DisableColor(). Otherwise this method has no side effects. +func (c *Color) EnableColor() { + c.noColor = boolPtr(false) +} + +func (c *Color) isNoColorSet() bool { + // check first if we have user setted action + if c.noColor != nil { + return *c.noColor + } + + // if not return the global option, which is disabled by default + return NoColor +} + +// Equals returns a boolean value indicating whether two colors are equal. +func (c *Color) Equals(c2 *Color) bool { + if len(c.params) != len(c2.params) { + return false + } + + for _, attr := range c.params { + if !c2.attrExists(attr) { + return false + } + } + + return true +} + +func (c *Color) attrExists(a Attribute) bool { + for _, attr := range c.params { + if attr == a { + return true + } + } + + return false +} + +func boolPtr(v bool) *bool { + return &v +} + +func getCachedColor(p Attribute) *Color { + colorsCacheMu.Lock() + defer colorsCacheMu.Unlock() + + c, ok := colorsCache[p] + if !ok { + c = New(p) + colorsCache[p] = c + } + + return c +} + +func colorPrint(format string, p Attribute, a ...interface{}) { + c := getCachedColor(p) + + if !strings.HasSuffix(format, "\n") { + format += "\n" + } + + if len(a) == 0 { + c.Print(format) + } else { + c.Printf(format, a...) + } +} + +func colorString(format string, p Attribute, a ...interface{}) string { + c := getCachedColor(p) + + if len(a) == 0 { + return c.SprintFunc()(format) + } + + return c.SprintfFunc()(format, a...) +} + +// Black is an convenient helper function to print with black foreground. A +// newline is appended to format by default. +func Black(format string, a ...interface{}) { colorPrint(format, FgBlack, a...) } + +// Red is an convenient helper function to print with red foreground. A +// newline is appended to format by default. +func Red(format string, a ...interface{}) { colorPrint(format, FgRed, a...) } + +// Green is an convenient helper function to print with green foreground. A +// newline is appended to format by default. +func Green(format string, a ...interface{}) { colorPrint(format, FgGreen, a...) } + +// Yellow is an convenient helper function to print with yellow foreground. +// A newline is appended to format by default. +func Yellow(format string, a ...interface{}) { colorPrint(format, FgYellow, a...) } + +// Blue is an convenient helper function to print with blue foreground. A +// newline is appended to format by default. +func Blue(format string, a ...interface{}) { colorPrint(format, FgBlue, a...) } + +// Magenta is an convenient helper function to print with magenta foreground. +// A newline is appended to format by default. +func Magenta(format string, a ...interface{}) { colorPrint(format, FgMagenta, a...) } + +// Cyan is an convenient helper function to print with cyan foreground. A +// newline is appended to format by default. +func Cyan(format string, a ...interface{}) { colorPrint(format, FgCyan, a...) } + +// White is an convenient helper function to print with white foreground. A +// newline is appended to format by default. +func White(format string, a ...interface{}) { colorPrint(format, FgWhite, a...) } + +// BlackString is an convenient helper function to return a string with black +// foreground. +func BlackString(format string, a ...interface{}) string { return colorString(format, FgBlack, a...) } + +// RedString is an convenient helper function to return a string with red +// foreground. +func RedString(format string, a ...interface{}) string { return colorString(format, FgRed, a...) } + +// GreenString is an convenient helper function to return a string with green +// foreground. +func GreenString(format string, a ...interface{}) string { return colorString(format, FgGreen, a...) } + +// YellowString is an convenient helper function to return a string with yellow +// foreground. +func YellowString(format string, a ...interface{}) string { return colorString(format, FgYellow, a...) } + +// BlueString is an convenient helper function to return a string with blue +// foreground. +func BlueString(format string, a ...interface{}) string { return colorString(format, FgBlue, a...) } + +// MagentaString is an convenient helper function to return a string with magenta +// foreground. +func MagentaString(format string, a ...interface{}) string { + return colorString(format, FgMagenta, a...) +} + +// CyanString is an convenient helper function to return a string with cyan +// foreground. +func CyanString(format string, a ...interface{}) string { return colorString(format, FgCyan, a...) } + +// WhiteString is an convenient helper function to return a string with white +// foreground. +func WhiteString(format string, a ...interface{}) string { return colorString(format, FgWhite, a...) } diff --git a/vendor/github.com/fatih/color/doc.go b/vendor/github.com/fatih/color/doc.go new file mode 100644 index 0000000..1e57812 --- /dev/null +++ b/vendor/github.com/fatih/color/doc.go @@ -0,0 +1,128 @@ +/* +Package color is an ANSI color package to output colorized or SGR defined +output to the standard output. The API can be used in several way, pick one +that suits you. + +Use simple and default helper functions with predefined foreground colors: + + color.Cyan("Prints text in cyan.") + + // a newline will be appended automatically + color.Blue("Prints %s in blue.", "text") + + // More default foreground colors.. + color.Red("We have red") + color.Yellow("Yellow color too!") + color.Magenta("And many others ..") + +However there are times where custom color mixes are required. Below are some +examples to create custom color objects and use the print functions of each +separate color object. + + // Create a new color object + c := color.New(color.FgCyan).Add(color.Underline) + c.Println("Prints cyan text with an underline.") + + // Or just add them to New() + d := color.New(color.FgCyan, color.Bold) + d.Printf("This prints bold cyan %s\n", "too!.") + + + // Mix up foreground and background colors, create new mixes! + red := color.New(color.FgRed) + + boldRed := red.Add(color.Bold) + boldRed.Println("This will print text in bold red.") + + whiteBackground := red.Add(color.BgWhite) + whiteBackground.Println("Red text with White background.") + + // Use your own io.Writer output + color.New(color.FgBlue).Fprintln(myWriter, "blue color!") + + blue := color.New(color.FgBlue) + blue.Fprint(myWriter, "This will print text in blue.") + +You can create PrintXxx functions to simplify even more: + + // Create a custom print function for convenient + red := color.New(color.FgRed).PrintfFunc() + red("warning") + red("error: %s", err) + + // Mix up multiple attributes + notice := color.New(color.Bold, color.FgGreen).PrintlnFunc() + notice("don't forget this...") + +You can also FprintXxx functions to pass your own io.Writer: + + blue := color.New(FgBlue).FprintfFunc() + blue(myWriter, "important notice: %s", stars) + + // Mix up with multiple attributes + success := color.New(color.Bold, color.FgGreen).FprintlnFunc() + success(myWriter, don't forget this...") + + +Or create SprintXxx functions to mix strings with other non-colorized strings: + + yellow := New(FgYellow).SprintFunc() + red := New(FgRed).SprintFunc() + + fmt.Printf("this is a %s and this is %s.\n", yellow("warning"), red("error")) + + info := New(FgWhite, BgGreen).SprintFunc() + fmt.Printf("this %s rocks!\n", info("package")) + +Windows support is enabled by default. All Print functions works as intended. +However only for color.SprintXXX functions, user should use fmt.FprintXXX and +set the output to color.Output: + + fmt.Fprintf(color.Output, "Windows support: %s", color.GreenString("PASS")) + + info := New(FgWhite, BgGreen).SprintFunc() + fmt.Fprintf(color.Output, "this %s rocks!\n", info("package")) + +Using with existing code is possible. Just use the Set() method to set the +standard output to the given parameters. That way a rewrite of an existing +code is not required. + + // Use handy standard colors. + color.Set(color.FgYellow) + + fmt.Println("Existing text will be now in Yellow") + fmt.Printf("This one %s\n", "too") + + color.Unset() // don't forget to unset + + // You can mix up parameters + color.Set(color.FgMagenta, color.Bold) + defer color.Unset() // use it in your function + + fmt.Println("All text will be now bold magenta.") + +There might be a case where you want to disable color output (for example to +pipe the standard output of your app to somewhere else). `Color` has support to +disable colors both globally and for single color definition. For example +suppose you have a CLI app and a `--no-color` bool flag. You can easily disable +the color output with: + + var flagNoColor = flag.Bool("no-color", false, "Disable color output") + + if *flagNoColor { + color.NoColor = true // disables colorized output + } + +It also has support for single color definitions (local). You can +disable/enable color output on the fly: + + c := color.New(color.FgCyan) + c.Println("Prints cyan text") + + c.DisableColor() + c.Println("This is printed without any color") + + c.EnableColor() + c.Println("This prints again cyan...") +*/ +package color diff --git a/vendor/github.com/fsnotify/fsnotify/fsnotify.go b/vendor/github.com/fsnotify/fsnotify/fsnotify.go index e7f55fe..190bf0d 100644 --- a/vendor/github.com/fsnotify/fsnotify/fsnotify.go +++ b/vendor/github.com/fsnotify/fsnotify/fsnotify.go @@ -9,6 +9,7 @@ package fsnotify import ( "bytes" + "errors" "fmt" ) @@ -60,3 +61,6 @@ func (op Op) String() string { func (e Event) String() string { return fmt.Sprintf("%q: %s", e.Name, e.Op.String()) } + +// Common errors that can be reported by a watcher +var ErrEventOverflow = errors.New("fsnotify queue overflow") diff --git a/vendor/github.com/fsnotify/fsnotify/inotify.go b/vendor/github.com/fsnotify/fsnotify/inotify.go index f3b74c5..bfa9dbc 100644 --- a/vendor/github.com/fsnotify/fsnotify/inotify.go +++ b/vendor/github.com/fsnotify/fsnotify/inotify.go @@ -245,6 +245,15 @@ func (w *Watcher) readEvents() { mask := uint32(raw.Mask) nameLen := uint32(raw.Len) + + if mask&unix.IN_Q_OVERFLOW != 0 { + select { + case w.Errors <- ErrEventOverflow: + case <-w.done: + return + } + } + // If the event happened to the watched directory or the watched file, the kernel // doesn't append the filename to the event, but we would like to always fill the // the "Name" field with a valid filename. We retrieve the path of the watch from diff --git a/vendor/github.com/gin-gonic/gin/README.md b/vendor/github.com/gin-gonic/gin/README.md index 8023dc5..82ea6a5 100644 --- a/vendor/github.com/gin-gonic/gin/README.md +++ b/vendor/github.com/gin-gonic/gin/README.md @@ -1,16 +1,15 @@ #Gin Web Framework + [![Build Status](https://travis-ci.org/gin-gonic/gin.svg)](https://travis-ci.org/gin-gonic/gin) -[![Coverage Status](https://coveralls.io/repos/gin-gonic/gin/badge.svg?branch=master)](https://coveralls.io/r/gin-gonic/gin?branch=master) +[![codecov](https://codecov.io/gh/gin-gonic/gin/branch/master/graph/badge.svg)](https://codecov.io/gh/gin-gonic/gin) [![Go Report Card](https://goreportcard.com/badge/github.com/gin-gonic/gin)](https://goreportcard.com/report/github.com/gin-gonic/gin) [![GoDoc](https://godoc.org/github.com/gin-gonic/gin?status.svg)](https://godoc.org/github.com/gin-gonic/gin) [![Join the chat at https://gitter.im/gin-gonic/gin](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/gin-gonic/gin?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) Gin is a web framework written in Go (Golang). It features a martini-like API with much better performance, up to 40 times faster thanks to [httprouter](https://github.com/julienschmidt/httprouter). If you need performance and good productivity, you will love Gin. - - ![Gin console logger](https://gin-gonic.github.io/gin/other/console.png) ```sh @@ -19,7 +18,7 @@ $ cat test.go ```go package main -import "github.com/gin-gonic/gin" +import "gopkg.in/gin-gonic/gin.v1" func main() { r := gin.Default() @@ -28,7 +27,7 @@ func main() { "message": "pong", }) }) - r.Run() // listen and server on 0.0.0.0:8080 + r.Run() // listen and serve on 0.0.0.0:8080 } ``` @@ -88,13 +87,13 @@ BenchmarkZeus_GithubAll | 2000 | 944234 | 300688 | 2648 1. Download and install it: ```sh - $ go get github.com/gin-gonic/gin + $ go get gopkg.in/gin-gonic/gin.v1 ``` 2. Import it in your code: ```go - import "github.com/gin-gonic/gin" + import "gopkg.in/gin-gonic/gin.v1" ``` 3. (Optional) Import `net/http`. This is required for example if using constants such as `http.StatusOK`. @@ -317,7 +316,7 @@ func main() { testing.GET("/analytics", analyticsEndpoint) } - // Listen and server on 0.0.0.0:8080 + // Listen and serve on 0.0.0.0:8080 r.Run(":8080") } ``` @@ -367,7 +366,7 @@ func main() { } }) - // Listen and server on 0.0.0.0:8080 + // Listen and serve on 0.0.0.0:8080 router.Run(":8080") } ``` @@ -378,8 +377,7 @@ func main() { package main import ( - "github.com/gin-gonic/gin" - "github.com/gin-gonic/gin/binding" + "gopkg.in/gin-gonic/gin.v1" ) type LoginForm struct { @@ -447,7 +445,7 @@ func main() { c.YAML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK}) }) - // Listen and server on 0.0.0.0:8080 + // Listen and serve on 0.0.0.0:8080 r.Run(":8080") } ``` @@ -461,7 +459,7 @@ func main() { router.StaticFS("/more_static", http.Dir("my_file_system")) router.StaticFile("/favicon.ico", "./resources/favicon.ico") - // Listen and server on 0.0.0.0:8080 + // Listen and serve on 0.0.0.0:8080 router.Run(":8080") } ``` @@ -593,7 +591,7 @@ func main() { log.Println(example) }) - // Listen and server on 0.0.0.0:8080 + // Listen and serve on 0.0.0.0:8080 r.Run(":8080") } ``` @@ -631,7 +629,7 @@ func main() { } }) - // Listen and server on 0.0.0.0:8080 + // Listen and serve on 0.0.0.0:8080 r.Run(":8080") } ``` @@ -664,7 +662,7 @@ func main() { log.Println("Done! in path " + c.Request.URL.Path) }) - // Listen and server on 0.0.0.0:8080 + // Listen and serve on 0.0.0.0:8080 r.Run(":8080") } ``` @@ -714,6 +712,19 @@ An alternative to endless: * [manners](https://github.com/braintree/manners): A polite Go HTTP server that shuts down gracefully. +## Contributing + +- With issues: + - Use the search tool before opening a new issue. + - Please provide source code and commit sha if you found a bug. + - Review existing issues and provide feedback or react to them. +- With pull requests: + - Open your pull request against develop + - Your pull request should have no more than two commits, if not you should squash them. + - It should pass all tests in the available continuous integrations systems such as TravisCI. + - You should add/modify tests to cover your proposed code changes. + - If your pull request contains a new feature, please document it on the README. + ## Example Awesome project lists using [Gin](https://github.com/gin-gonic/gin) web framework. diff --git a/vendor/github.com/gin-gonic/gin/codecov.yml b/vendor/github.com/gin-gonic/gin/codecov.yml new file mode 100644 index 0000000..c9c9a52 --- /dev/null +++ b/vendor/github.com/gin-gonic/gin/codecov.yml @@ -0,0 +1,5 @@ +coverage: + notify: + gitter: + default: + url: https://webhooks.gitter.im/e/d90dcdeeab2f1e357165 diff --git a/vendor/github.com/gin-gonic/gin/context.go b/vendor/github.com/gin-gonic/gin/context.go index 5d3b6a4..df001a4 100644 --- a/vendor/github.com/gin-gonic/gin/context.go +++ b/vendor/github.com/gin-gonic/gin/context.go @@ -230,11 +230,27 @@ func (c *Context) DefaultQuery(key, defaultValue string) string { // ("", false) == c.GetQuery("id") // ("", true) == c.GetQuery("lastname") func (c *Context) GetQuery(key string) (string, bool) { + if values, ok := c.GetQueryArray(key); ok { + return values[0], ok + } + return "", false +} + +// QueryArray returns a slice of strings for a given query key. +// The length of the slice depends on the number of params with the given key. +func (c *Context) QueryArray(key string) []string { + values, _ := c.GetQueryArray(key) + return values +} + +// GetQueryArray returns a slice of strings for a given query key, plus +// a boolean value whether at least one value exists for the given key. +func (c *Context) GetQueryArray(key string) ([]string, bool) { req := c.Request if values, ok := req.URL.Query()[key]; ok && len(values) > 0 { - return values[0], true + return values, true } - return "", false + return []string{}, false } // PostForm returns the specified key from a POST urlencoded form or multipart form @@ -262,17 +278,34 @@ func (c *Context) DefaultPostForm(key, defaultValue string) string { // email= --> ("", true) := GetPostForm("email") // set email to "" // --> ("", false) := GetPostForm("email") // do nothing with email func (c *Context) GetPostForm(key string) (string, bool) { + if values, ok := c.GetPostFormArray(key); ok { + return values[0], ok + } + return "", false +} + +// PostFormArray returns a slice of strings for a given form key. +// The length of the slice depends on the number of params with the given key. +func (c *Context) PostFormArray(key string) []string { + values, _ := c.GetPostFormArray(key) + return values +} + +// GetPostFormArray returns a slice of strings for a given form key, plus +// a boolean value whether at least one value exists for the given key. +func (c *Context) GetPostFormArray(key string) ([]string, bool) { req := c.Request + req.ParseForm() req.ParseMultipartForm(32 << 20) // 32 MB if values := req.PostForm[key]; len(values) > 0 { - return values[0], true + return values, true } if req.MultipartForm != nil && req.MultipartForm.File != nil { if values := req.MultipartForm.Value[key]; len(values) > 0 { - return values[0], true + return values, true } } - return "", false + return []string{}, false } // Bind checks the Content-Type to select a binding engine automatically, diff --git a/vendor/github.com/gin-gonic/gin/logger.go b/vendor/github.com/gin-gonic/gin/logger.go index d56bc62..7c2a72b 100644 --- a/vendor/github.com/gin-gonic/gin/logger.go +++ b/vendor/github.com/gin-gonic/gin/logger.go @@ -7,7 +7,10 @@ package gin import ( "fmt" "io" + "os" "time" + + "github.com/mattn/go-isatty" ) var ( @@ -44,6 +47,12 @@ func Logger() HandlerFunc { // LoggerWithWriter instance a Logger middleware with the specified writter buffer. // Example: os.Stdout, a file opened in write mode, a socket... func LoggerWithWriter(out io.Writer, notlogged ...string) HandlerFunc { + isTerm := true + + if w, ok := out.(*os.File); !ok || !isatty.IsTerminal(w.Fd()) { + isTerm = false + } + var skip map[string]struct{} if length := len(notlogged); length > 0 { @@ -71,8 +80,11 @@ func LoggerWithWriter(out io.Writer, notlogged ...string) HandlerFunc { clientIP := c.ClientIP() method := c.Request.Method statusCode := c.Writer.Status() - statusColor := colorForStatus(statusCode) - methodColor := colorForMethod(method) + var statusColor, methodColor string + if isTerm { + statusColor = colorForStatus(statusCode) + methodColor = colorForMethod(method) + } comment := c.Errors.ByType(ErrorTypePrivate).String() fmt.Fprintf(out, "[GIN] %v |%s %3d %s| %13v | %s |%s %s %-7s %s\n%s", diff --git a/vendor/github.com/gin-gonic/gin/mode.go b/vendor/github.com/gin-gonic/gin/mode.go index f44b071..c600b7b 100644 --- a/vendor/github.com/gin-gonic/gin/mode.go +++ b/vendor/github.com/gin-gonic/gin/mode.go @@ -20,8 +20,8 @@ const ( ) const ( debugCode = iota - releaseCode = iota - testCode = iota + releaseCode + testCode ) // DefaultWriter is the default io.Writer used the Gin for debug output and diff --git a/vendor/github.com/golang/protobuf/proto/decode.go b/vendor/github.com/golang/protobuf/proto/decode.go index 07288a2..aa20729 100644 --- a/vendor/github.com/golang/protobuf/proto/decode.go +++ b/vendor/github.com/golang/protobuf/proto/decode.go @@ -61,7 +61,6 @@ var ErrInternalBadWireType = errors.New("proto: internal error: bad wiretype for // int32, int64, uint32, uint64, bool, and enum // protocol buffer types. func DecodeVarint(buf []byte) (x uint64, n int) { - // x, n already 0 for shift := uint(0); shift < 64; shift += 7 { if n >= len(buf) { return 0, 0 @@ -78,13 +77,7 @@ func DecodeVarint(buf []byte) (x uint64, n int) { return 0, 0 } -// DecodeVarint reads a varint-encoded integer from the Buffer. -// This is the format for the -// int32, int64, uint32, uint64, bool, and enum -// protocol buffer types. -func (p *Buffer) DecodeVarint() (x uint64, err error) { - // x, err already 0 - +func (p *Buffer) decodeVarintSlow() (x uint64, err error) { i := p.index l := len(p.buf) @@ -107,6 +100,107 @@ func (p *Buffer) DecodeVarint() (x uint64, err error) { return } +// DecodeVarint reads a varint-encoded integer from the Buffer. +// This is the format for the +// int32, int64, uint32, uint64, bool, and enum +// protocol buffer types. +func (p *Buffer) DecodeVarint() (x uint64, err error) { + i := p.index + buf := p.buf + + if i >= len(buf) { + return 0, io.ErrUnexpectedEOF + } else if buf[i] < 0x80 { + p.index++ + return uint64(buf[i]), nil + } else if len(buf)-i < 10 { + return p.decodeVarintSlow() + } + + var b uint64 + // we already checked the first byte + x = uint64(buf[i]) - 0x80 + i++ + + b = uint64(buf[i]) + i++ + x += b << 7 + if b&0x80 == 0 { + goto done + } + x -= 0x80 << 7 + + b = uint64(buf[i]) + i++ + x += b << 14 + if b&0x80 == 0 { + goto done + } + x -= 0x80 << 14 + + b = uint64(buf[i]) + i++ + x += b << 21 + if b&0x80 == 0 { + goto done + } + x -= 0x80 << 21 + + b = uint64(buf[i]) + i++ + x += b << 28 + if b&0x80 == 0 { + goto done + } + x -= 0x80 << 28 + + b = uint64(buf[i]) + i++ + x += b << 35 + if b&0x80 == 0 { + goto done + } + x -= 0x80 << 35 + + b = uint64(buf[i]) + i++ + x += b << 42 + if b&0x80 == 0 { + goto done + } + x -= 0x80 << 42 + + b = uint64(buf[i]) + i++ + x += b << 49 + if b&0x80 == 0 { + goto done + } + x -= 0x80 << 49 + + b = uint64(buf[i]) + i++ + x += b << 56 + if b&0x80 == 0 { + goto done + } + x -= 0x80 << 56 + + b = uint64(buf[i]) + i++ + x += b << 63 + if b&0x80 == 0 { + goto done + } + // x -= 0x80 << 63 // Always zero. + + return 0, errOverflow + +done: + p.index = i + return x, nil +} + // DecodeFixed64 reads a 64-bit integer from the Buffer. // This is the format for the // fixed64, sfixed64, and double protocol buffer types. @@ -340,6 +434,8 @@ func (p *Buffer) DecodeGroup(pb Message) error { // Buffer and places the decoded result in pb. If the struct // underlying pb does not match the data in the buffer, the results can be // unpredictable. +// +// Unlike proto.Unmarshal, this does not reset pb before starting to unmarshal. func (p *Buffer) Unmarshal(pb Message) error { // If the object can unmarshal itself, let it. if u, ok := pb.(Unmarshaler); ok { @@ -378,6 +474,11 @@ func (o *Buffer) unmarshalType(st reflect.Type, prop *StructProperties, is_group wire := int(u & 0x7) if wire == WireEndGroup { if is_group { + if required > 0 { + // Not enough information to determine the exact field. + // (See below.) + return &RequiredNotSetError{"{Unknown}"} + } return nil // input is satisfied } return fmt.Errorf("proto: %s: wiretype end group for non-group", st) diff --git a/vendor/github.com/golang/protobuf/proto/encode.go b/vendor/github.com/golang/protobuf/proto/encode.go index 8c1b8fd..2b30f84 100644 --- a/vendor/github.com/golang/protobuf/proto/encode.go +++ b/vendor/github.com/golang/protobuf/proto/encode.go @@ -234,10 +234,6 @@ func Marshal(pb Message) ([]byte, error) { } p := NewBuffer(nil) err := p.Marshal(pb) - var state errorState - if err != nil && !state.shouldContinue(err, nil) { - return nil, err - } if p.buf == nil && err == nil { // Return a non-nil slice on success. return []byte{}, nil @@ -266,11 +262,8 @@ func (p *Buffer) Marshal(pb Message) error { // Can the object marshal itself? if m, ok := pb.(Marshaler); ok { data, err := m.Marshal() - if err != nil { - return err - } p.buf = append(p.buf, data...) - return nil + return err } t, base, err := getbase(pb) @@ -282,7 +275,7 @@ func (p *Buffer) Marshal(pb Message) error { } if collectStats { - stats.Encode++ + (stats).Encode++ // Parens are to work around a goimports bug. } if len(p.buf) > maxMarshalSize { @@ -309,7 +302,7 @@ func Size(pb Message) (n int) { } if collectStats { - stats.Size++ + (stats).Size++ // Parens are to work around a goimports bug. } return @@ -1014,7 +1007,6 @@ func size_slice_struct_message(p *Properties, base structPointer) (n int) { if p.isMarshaler { m := structPointer_Interface(structp, p.stype).(Marshaler) data, _ := m.Marshal() - n += len(p.tagcode) n += sizeRawBytes(data) continue } @@ -1083,10 +1075,17 @@ func (o *Buffer) enc_map(p *Properties, base structPointer) error { func (o *Buffer) enc_exts(p *Properties, base structPointer) error { exts := structPointer_Extensions(base, p.field) - if err := encodeExtensions(exts); err != nil { + + v, mu := exts.extensionsRead() + if v == nil { + return nil + } + + mu.Lock() + defer mu.Unlock() + if err := encodeExtensionsMap(v); err != nil { return err } - v, _ := exts.extensionsRead() return o.enc_map_body(v) } diff --git a/vendor/github.com/golang/protobuf/proto/equal.go b/vendor/github.com/golang/protobuf/proto/equal.go index 8b16f95..2ed1cf5 100644 --- a/vendor/github.com/golang/protobuf/proto/equal.go +++ b/vendor/github.com/golang/protobuf/proto/equal.go @@ -54,13 +54,17 @@ Equality is defined in this way: in a proto3 .proto file, fields are not "set"; specifically, zero length proto3 "bytes" fields are equal (nil == {}). - Two repeated fields are equal iff their lengths are the same, - and their corresponding elements are equal (a "bytes" field, - although represented by []byte, is not a repeated field) + and their corresponding elements are equal. Note a "bytes" field, + although represented by []byte, is not a repeated field and the + rule for the scalar fields described above applies. - Two unset fields are equal. - Two unknown field sets are equal if their current encoded state is equal. - Two extension sets are equal iff they have corresponding elements that are pairwise equal. + - Two map fields are equal iff their lengths are the same, + and they contain the same set of elements. Zero-length map + fields are equal. - Every other combination of things are not equal. The return value is undefined if a and b are not protocol buffers. diff --git a/vendor/github.com/golang/protobuf/proto/extensions.go b/vendor/github.com/golang/protobuf/proto/extensions.go index 482f3e9..eaad218 100644 --- a/vendor/github.com/golang/protobuf/proto/extensions.go +++ b/vendor/github.com/golang/protobuf/proto/extensions.go @@ -154,6 +154,7 @@ type ExtensionDesc struct { Field int32 // field number Name string // fully-qualified name of extension, for text formatting Tag string // protobuf tag style + Filename string // name of the file in which the extension is defined } func (ed *ExtensionDesc) repeated() bool { @@ -500,6 +501,9 @@ func ExtensionDescs(pb Message) ([]*ExtensionDesc, error) { registeredExtensions := RegisteredExtensions(pb) emap, mu := epb.extensionsRead() + if emap == nil { + return nil, nil + } mu.Lock() defer mu.Unlock() extensions := make([]*ExtensionDesc, 0, len(emap)) diff --git a/vendor/github.com/golang/protobuf/proto/lib.go b/vendor/github.com/golang/protobuf/proto/lib.go index 170b8e8..ac4ddbc 100644 --- a/vendor/github.com/golang/protobuf/proto/lib.go +++ b/vendor/github.com/golang/protobuf/proto/lib.go @@ -308,7 +308,7 @@ func GetStats() Stats { return stats } // temporary Buffer and are fine for most applications. type Buffer struct { buf []byte // encode/decode byte stream - index int // write point + index int // read point // pools of basic types to amortize allocation. bools []bool diff --git a/vendor/github.com/golang/protobuf/proto/properties.go b/vendor/github.com/golang/protobuf/proto/properties.go index 69ddda8..ec2289c 100644 --- a/vendor/github.com/golang/protobuf/proto/properties.go +++ b/vendor/github.com/golang/protobuf/proto/properties.go @@ -844,7 +844,15 @@ func RegisterType(x Message, name string) { } // MessageName returns the fully-qualified proto name for the given message type. -func MessageName(x Message) string { return revProtoTypes[reflect.TypeOf(x)] } +func MessageName(x Message) string { + type xname interface { + XXX_MessageName() string + } + if m, ok := x.(xname); ok { + return m.XXX_MessageName() + } + return revProtoTypes[reflect.TypeOf(x)] +} // MessageType returns the message type (pointer to struct) for a named message. func MessageType(name string) reflect.Type { return protoTypes[name] } diff --git a/vendor/github.com/golang/protobuf/proto/text_parser.go b/vendor/github.com/golang/protobuf/proto/text_parser.go index 0b8c59f..61f83c1 100644 --- a/vendor/github.com/golang/protobuf/proto/text_parser.go +++ b/vendor/github.com/golang/protobuf/proto/text_parser.go @@ -44,6 +44,9 @@ import ( "unicode/utf8" ) +// Error string emitted when deserializing Any and fields are already set +const anyRepeatedlyUnpacked = "Any message unpacked multiple times, or %q already set" + type ParseError struct { Message string Line int // 1-based line number @@ -508,8 +511,16 @@ func (p *textParser) readStruct(sv reflect.Value, terminator string) error { if err != nil { return p.errorf("failed to marshal message of type %q: %v", messageName, err) } + if fieldSet["type_url"] { + return p.errorf(anyRepeatedlyUnpacked, "type_url") + } + if fieldSet["value"] { + return p.errorf(anyRepeatedlyUnpacked, "value") + } sv.FieldByName("TypeUrl").SetString(extName) sv.FieldByName("Value").SetBytes(b) + fieldSet["type_url"] = true + fieldSet["value"] = true continue } @@ -581,7 +592,11 @@ func (p *textParser) readStruct(sv reflect.Value, terminator string) error { props = oop.Prop nv := reflect.New(oop.Type.Elem()) dst = nv.Elem().Field(0) - sv.Field(oop.Field).Set(nv) + field := sv.Field(oop.Field) + if !field.IsNil() { + return p.errorf("field '%s' would overwrite already parsed oneof '%s'", name, sv.Type().Field(oop.Field).Name) + } + field.Set(nv) } if !dst.IsValid() { return p.errorf("unknown field name %q in %v", name, st) @@ -781,12 +796,12 @@ func (p *textParser) readAny(v reflect.Value, props *Properties) error { fv.Set(reflect.Append(fv, reflect.New(at.Elem()).Elem())) return p.readAny(fv.Index(fv.Len()-1), props) case reflect.Bool: - // Either "true", "false", 1 or 0. + // true/1/t/True or false/f/0/False. switch tok.value { - case "true", "1": + case "true", "1", "t", "True": fv.SetBool(true) return nil - case "false", "0": + case "false", "0", "f", "False": fv.SetBool(false) return nil } diff --git a/vendor/github.com/hashicorp/hcl/decoder.go b/vendor/github.com/hashicorp/hcl/decoder.go index c8a077d..0b39c1b 100644 --- a/vendor/github.com/hashicorp/hcl/decoder.go +++ b/vendor/github.com/hashicorp/hcl/decoder.go @@ -91,7 +91,7 @@ func (d *decoder) decode(name string, node ast.Node, result reflect.Value) error return d.decodeBool(name, node, result) case reflect.Float64: return d.decodeFloat(name, node, result) - case reflect.Int: + case reflect.Int, reflect.Int32, reflect.Int64: return d.decodeInt(name, node, result) case reflect.Interface: // When we see an interface, we make our own thing @@ -164,7 +164,11 @@ func (d *decoder) decodeInt(name string, node ast.Node, result reflect.Value) er return err } - result.Set(reflect.ValueOf(int(v))) + if result.Kind() == reflect.Interface { + result.Set(reflect.ValueOf(int(v))) + } else { + result.SetInt(v) + } return nil case token.STRING: v, err := strconv.ParseInt(n.Token.Value().(string), 0, 0) @@ -172,7 +176,11 @@ func (d *decoder) decodeInt(name string, node ast.Node, result reflect.Value) er return err } - result.Set(reflect.ValueOf(int(v))) + if result.Kind() == reflect.Interface { + result.Set(reflect.ValueOf(int(v))) + } else { + result.SetInt(v) + } return nil } } diff --git a/vendor/github.com/hashicorp/hcl/hcl/parser/parser.go b/vendor/github.com/hashicorp/hcl/hcl/parser/parser.go index 0aa080f..8dd73e0 100644 --- a/vendor/github.com/hashicorp/hcl/hcl/parser/parser.go +++ b/vendor/github.com/hashicorp/hcl/hcl/parser/parser.go @@ -50,7 +50,7 @@ func (p *Parser) Parse() (*ast.File, error) { scerr = &PosError{Pos: pos, Err: errors.New(msg)} } - f.Node, err = p.objectList() + f.Node, err = p.objectList(false) if scerr != nil { return nil, scerr } @@ -62,11 +62,23 @@ func (p *Parser) Parse() (*ast.File, error) { return f, nil } -func (p *Parser) objectList() (*ast.ObjectList, error) { +// objectList parses a list of items within an object (generally k/v pairs). +// The parameter" obj" tells this whether to we are within an object (braces: +// '{', '}') or just at the top level. If we're within an object, we end +// at an RBRACE. +func (p *Parser) objectList(obj bool) (*ast.ObjectList, error) { defer un(trace(p, "ParseObjectList")) node := &ast.ObjectList{} for { + if obj { + tok := p.scan() + p.unscan() + if tok.Type == token.RBRACE { + break + } + } + n, err := p.objectItem() if err == errEofToken { break // we are finished @@ -244,7 +256,10 @@ func (p *Parser) objectKey() ([]*ast.ObjectKey, error) { keyCount++ keys = append(keys, &ast.ObjectKey{Token: p.tok}) case token.ILLEGAL: - fmt.Println("illegal") + return keys, &PosError{ + Pos: p.tok.Pos, + Err: fmt.Errorf("illegal character"), + } default: return keys, &PosError{ Pos: p.tok.Pos, @@ -288,7 +303,7 @@ func (p *Parser) objectType() (*ast.ObjectType, error) { Lbrace: p.tok.Pos, } - l, err := p.objectList() + l, err := p.objectList(true) // if we hit RBRACE, we are good to go (means we parsed all Items), if it's // not a RBRACE, it's an syntax error and we just return it. @@ -296,9 +311,9 @@ func (p *Parser) objectType() (*ast.ObjectType, error) { return nil, err } - // If there is no error, we should be at a RBRACE to end the object - if p.tok.Type != token.RBRACE { - return nil, fmt.Errorf("object expected closing RBRACE got: %s", p.tok.Type) + // No error, scan and expect the ending to be a brace + if tok := p.scan(); tok.Type != token.RBRACE { + return nil, fmt.Errorf("object expected closing RBRACE got: %s", tok.Type) } o.List = l @@ -331,7 +346,7 @@ func (p *Parser) listType() (*ast.ListType, error) { } } switch tok.Type { - case token.NUMBER, token.FLOAT, token.STRING, token.HEREDOC: + case token.BOOL, token.NUMBER, token.FLOAT, token.STRING, token.HEREDOC: node, err := p.literalType() if err != nil { return nil, err @@ -373,8 +388,6 @@ func (p *Parser) listType() (*ast.ListType, error) { } l.Add(node) needComma = true - case token.BOOL: - // TODO(arslan) should we support? not supported by HCL yet case token.LBRACK: // TODO(arslan) should we support nested lists? Even though it's // written in README of HCL, it's not a part of the grammar diff --git a/vendor/github.com/hashicorp/hcl/hcl/scanner/scanner.go b/vendor/github.com/hashicorp/hcl/hcl/scanner/scanner.go index 0735d95..6966236 100644 --- a/vendor/github.com/hashicorp/hcl/hcl/scanner/scanner.go +++ b/vendor/github.com/hashicorp/hcl/hcl/scanner/scanner.go @@ -95,6 +95,12 @@ func (s *Scanner) next() rune { s.srcPos.Column = 0 } + // If we see a null character with data left, then that is an error + if ch == '\x00' && s.buf.Len() > 0 { + s.err("unexpected null character (0x00)") + return eof + } + // debug // fmt.Printf("ch: %q, offset:column: %d:%d\n", ch, s.srcPos.Offset, s.srcPos.Column) return ch @@ -474,7 +480,7 @@ func (s *Scanner) scanString() { // read character after quote ch := s.next() - if ch < 0 || ch == eof { + if (ch == '\n' && braces == 0) || ch < 0 || ch == eof { s.err("literal not terminated") return } diff --git a/vendor/github.com/hashicorp/hcl/hcl/strconv/quote.go b/vendor/github.com/hashicorp/hcl/hcl/strconv/quote.go index 956c899..5f981ea 100644 --- a/vendor/github.com/hashicorp/hcl/hcl/strconv/quote.go +++ b/vendor/github.com/hashicorp/hcl/hcl/strconv/quote.go @@ -27,6 +27,9 @@ func Unquote(s string) (t string, err error) { if quote != '"' { return "", ErrSyntax } + if !contains(s, '$') && !contains(s, '{') && contains(s, '\n') { + return "", ErrSyntax + } // Is it trivial? Avoid allocation. if !contains(s, '\\') && !contains(s, quote) && !contains(s, '$') { @@ -46,7 +49,7 @@ func Unquote(s string) (t string, err error) { for len(s) > 0 { // If we're starting a '${}' then let it through un-unquoted. // Specifically: we don't unquote any characters within the `${}` - // section, except for escaped backslashes, which we handle specifically. + // section. if s[0] == '$' && len(s) > 1 && s[1] == '{' { buf = append(buf, '$', '{') s = s[2:] @@ -61,16 +64,6 @@ func Unquote(s string) (t string, err error) { s = s[size:] - // We special case escaped backslashes in interpolations, converting - // them to their unescaped equivalents. - if r == '\\' { - q, _ := utf8.DecodeRuneInString(s) - switch q { - case '\\': - continue - } - } - n := utf8.EncodeRune(runeTmp[:], r) buf = append(buf, runeTmp[:n]...) @@ -94,6 +87,10 @@ func Unquote(s string) (t string, err error) { } } + if s[0] == '\n' { + return "", ErrSyntax + } + c, multibyte, ss, err := unquoteChar(s, quote) if err != nil { return "", err diff --git a/vendor/github.com/hashicorp/hcl/json/parser/flatten.go b/vendor/github.com/hashicorp/hcl/json/parser/flatten.go index 6eb14a2..f652d6f 100644 --- a/vendor/github.com/hashicorp/hcl/json/parser/flatten.go +++ b/vendor/github.com/hashicorp/hcl/json/parser/flatten.go @@ -48,6 +48,12 @@ func flattenListType( item *ast.ObjectItem, items []*ast.ObjectItem, frontier []*ast.ObjectItem) ([]*ast.ObjectItem, []*ast.ObjectItem) { + // If the list is empty, keep the original list + if len(ot.List) == 0 { + items = append(items, item) + return items, frontier + } + // All the elements of this object must also be objects! for _, subitem := range ot.List { if _, ok := subitem.(*ast.ObjectType); !ok { diff --git a/vendor/github.com/hashicorp/hcl/json/parser/parser.go b/vendor/github.com/hashicorp/hcl/json/parser/parser.go index acf9594..6f46085 100644 --- a/vendor/github.com/hashicorp/hcl/json/parser/parser.go +++ b/vendor/github.com/hashicorp/hcl/json/parser/parser.go @@ -86,6 +86,7 @@ func (p *Parser) objectList() (*ast.ObjectList, error) { break } } + return node, nil } diff --git a/vendor/github.com/inconshreveable/mousetrap/LICENSE b/vendor/github.com/inconshreveable/mousetrap/LICENSE deleted file mode 100644 index 5f0d1fb..0000000 --- a/vendor/github.com/inconshreveable/mousetrap/LICENSE +++ /dev/null @@ -1,13 +0,0 @@ -Copyright 2014 Alan Shreve - -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. diff --git a/vendor/github.com/inconshreveable/mousetrap/README.md b/vendor/github.com/inconshreveable/mousetrap/README.md deleted file mode 100644 index 7a950d1..0000000 --- a/vendor/github.com/inconshreveable/mousetrap/README.md +++ /dev/null @@ -1,23 +0,0 @@ -# mousetrap - -mousetrap is a tiny library that answers a single question. - -On a Windows machine, was the process invoked by someone double clicking on -the executable file while browsing in explorer? - -### Motivation - -Windows developers unfamiliar with command line tools will often "double-click" -the executable for a tool. Because most CLI tools print the help and then exit -when invoked without arguments, this is often very frustrating for those users. - -mousetrap provides a way to detect these invocations so that you can provide -more helpful behavior and instructions on how to run the CLI tool. To see what -this looks like, both from an organizational and a technical perspective, see -https://inconshreveable.com/09-09-2014/sweat-the-small-stuff/ - -### The interface - -The library exposes a single interface: - - func StartedByExplorer() (bool) diff --git a/vendor/github.com/inconshreveable/mousetrap/trap_others.go b/vendor/github.com/inconshreveable/mousetrap/trap_others.go deleted file mode 100644 index 9d2d8a4..0000000 --- a/vendor/github.com/inconshreveable/mousetrap/trap_others.go +++ /dev/null @@ -1,15 +0,0 @@ -// +build !windows - -package mousetrap - -// StartedByExplorer returns true if the program was invoked by the user -// double-clicking on the executable from explorer.exe -// -// It is conservative and returns false if any of the internal calls fail. -// It does not guarantee that the program was run from a terminal. It only can tell you -// whether it was launched from explorer.exe -// -// On non-Windows platforms, it always returns false. -func StartedByExplorer() bool { - return false -} diff --git a/vendor/github.com/inconshreveable/mousetrap/trap_windows.go b/vendor/github.com/inconshreveable/mousetrap/trap_windows.go deleted file mode 100644 index 336142a..0000000 --- a/vendor/github.com/inconshreveable/mousetrap/trap_windows.go +++ /dev/null @@ -1,98 +0,0 @@ -// +build windows -// +build !go1.4 - -package mousetrap - -import ( - "fmt" - "os" - "syscall" - "unsafe" -) - -const ( - // defined by the Win32 API - th32cs_snapprocess uintptr = 0x2 -) - -var ( - kernel = syscall.MustLoadDLL("kernel32.dll") - CreateToolhelp32Snapshot = kernel.MustFindProc("CreateToolhelp32Snapshot") - Process32First = kernel.MustFindProc("Process32FirstW") - Process32Next = kernel.MustFindProc("Process32NextW") -) - -// ProcessEntry32 structure defined by the Win32 API -type processEntry32 struct { - dwSize uint32 - cntUsage uint32 - th32ProcessID uint32 - th32DefaultHeapID int - th32ModuleID uint32 - cntThreads uint32 - th32ParentProcessID uint32 - pcPriClassBase int32 - dwFlags uint32 - szExeFile [syscall.MAX_PATH]uint16 -} - -func getProcessEntry(pid int) (pe *processEntry32, err error) { - snapshot, _, e1 := CreateToolhelp32Snapshot.Call(th32cs_snapprocess, uintptr(0)) - if snapshot == uintptr(syscall.InvalidHandle) { - err = fmt.Errorf("CreateToolhelp32Snapshot: %v", e1) - return - } - defer syscall.CloseHandle(syscall.Handle(snapshot)) - - var processEntry processEntry32 - processEntry.dwSize = uint32(unsafe.Sizeof(processEntry)) - ok, _, e1 := Process32First.Call(snapshot, uintptr(unsafe.Pointer(&processEntry))) - if ok == 0 { - err = fmt.Errorf("Process32First: %v", e1) - return - } - - for { - if processEntry.th32ProcessID == uint32(pid) { - pe = &processEntry - return - } - - ok, _, e1 = Process32Next.Call(snapshot, uintptr(unsafe.Pointer(&processEntry))) - if ok == 0 { - err = fmt.Errorf("Process32Next: %v", e1) - return - } - } -} - -func getppid() (pid int, err error) { - pe, err := getProcessEntry(os.Getpid()) - if err != nil { - return - } - - pid = int(pe.th32ParentProcessID) - return -} - -// StartedByExplorer returns true if the program was invoked by the user double-clicking -// on the executable from explorer.exe -// -// It is conservative and returns false if any of the internal calls fail. -// It does not guarantee that the program was run from a terminal. It only can tell you -// whether it was launched from explorer.exe -func StartedByExplorer() bool { - ppid, err := getppid() - if err != nil { - return false - } - - pe, err := getProcessEntry(ppid) - if err != nil { - return false - } - - name := syscall.UTF16ToString(pe.szExeFile[:]) - return name == "explorer.exe" -} diff --git a/vendor/github.com/inconshreveable/mousetrap/trap_windows_1.4.go b/vendor/github.com/inconshreveable/mousetrap/trap_windows_1.4.go deleted file mode 100644 index 9a28e57..0000000 --- a/vendor/github.com/inconshreveable/mousetrap/trap_windows_1.4.go +++ /dev/null @@ -1,46 +0,0 @@ -// +build windows -// +build go1.4 - -package mousetrap - -import ( - "os" - "syscall" - "unsafe" -) - -func getProcessEntry(pid int) (*syscall.ProcessEntry32, error) { - snapshot, err := syscall.CreateToolhelp32Snapshot(syscall.TH32CS_SNAPPROCESS, 0) - if err != nil { - return nil, err - } - defer syscall.CloseHandle(snapshot) - var procEntry syscall.ProcessEntry32 - procEntry.Size = uint32(unsafe.Sizeof(procEntry)) - if err = syscall.Process32First(snapshot, &procEntry); err != nil { - return nil, err - } - for { - if procEntry.ProcessID == uint32(pid) { - return &procEntry, nil - } - err = syscall.Process32Next(snapshot, &procEntry) - if err != nil { - return nil, err - } - } -} - -// StartedByExplorer returns true if the program was invoked by the user double-clicking -// on the executable from explorer.exe -// -// It is conservative and returns false if any of the internal calls fail. -// It does not guarantee that the program was run from a terminal. It only can tell you -// whether it was launched from explorer.exe -func StartedByExplorer() bool { - pe, err := getProcessEntry(os.Getppid()) - if err != nil { - return false - } - return "explorer.exe" == syscall.UTF16ToString(pe.ExeFile[:]) -} diff --git a/vendor/github.com/jinzhu/now/README.md b/vendor/github.com/jinzhu/now/README.md index 073c1c6..40b5975 100644 --- a/vendor/github.com/jinzhu/now/README.md +++ b/vendor/github.com/jinzhu/now/README.md @@ -91,6 +91,12 @@ now.TimeFormats = append(now.TimeFormats, "02 Jan 2006 15:04") Please send me pull requests if you want a format to be supported officially + +# Supporting the project + +[![http://patreon.com/jinzhu](http://patreon_public_assets.s3.amazonaws.com/sized/becomeAPatronBanner.png)](http://patreon.com/jinzhu) + + # Author **jinzhu** diff --git a/vendor/github.com/kr/fs/LICENSE b/vendor/github.com/kr/fs/LICENSE deleted file mode 100644 index 7448756..0000000 --- a/vendor/github.com/kr/fs/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -Copyright (c) 2012 The Go Authors. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of Google Inc. nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/kr/fs/Readme b/vendor/github.com/kr/fs/Readme deleted file mode 100644 index c95e13f..0000000 --- a/vendor/github.com/kr/fs/Readme +++ /dev/null @@ -1,3 +0,0 @@ -Filesystem Package - -http://godoc.org/github.com/kr/fs diff --git a/vendor/github.com/kr/fs/filesystem.go b/vendor/github.com/kr/fs/filesystem.go deleted file mode 100644 index f1c4805..0000000 --- a/vendor/github.com/kr/fs/filesystem.go +++ /dev/null @@ -1,36 +0,0 @@ -package fs - -import ( - "io/ioutil" - "os" - "path/filepath" -) - -// FileSystem defines the methods of an abstract filesystem. -type FileSystem interface { - - // ReadDir reads the directory named by dirname and returns a - // list of directory entries. - ReadDir(dirname string) ([]os.FileInfo, error) - - // Lstat returns a FileInfo describing the named file. If the file is a - // symbolic link, the returned FileInfo describes the symbolic link. Lstat - // makes no attempt to follow the link. - Lstat(name string) (os.FileInfo, error) - - // Join joins any number of path elements into a single path, adding a - // separator if necessary. The result is Cleaned; in particular, all - // empty strings are ignored. - // - // The separator is FileSystem specific. - Join(elem ...string) string -} - -// fs represents a FileSystem provided by the os package. -type fs struct{} - -func (f *fs) ReadDir(dirname string) ([]os.FileInfo, error) { return ioutil.ReadDir(dirname) } - -func (f *fs) Lstat(name string) (os.FileInfo, error) { return os.Lstat(name) } - -func (f *fs) Join(elem ...string) string { return filepath.Join(elem...) } diff --git a/vendor/github.com/kr/fs/walk.go b/vendor/github.com/kr/fs/walk.go deleted file mode 100644 index 6ffa1e0..0000000 --- a/vendor/github.com/kr/fs/walk.go +++ /dev/null @@ -1,95 +0,0 @@ -// Package fs provides filesystem-related functions. -package fs - -import ( - "os" -) - -// Walker provides a convenient interface for iterating over the -// descendants of a filesystem path. -// Successive calls to the Step method will step through each -// file or directory in the tree, including the root. The files -// are walked in lexical order, which makes the output deterministic -// but means that for very large directories Walker can be inefficient. -// Walker does not follow symbolic links. -type Walker struct { - fs FileSystem - cur item - stack []item - descend bool -} - -type item struct { - path string - info os.FileInfo - err error -} - -// Walk returns a new Walker rooted at root. -func Walk(root string) *Walker { - return WalkFS(root, new(fs)) -} - -// WalkFS returns a new Walker rooted at root on the FileSystem fs. -func WalkFS(root string, fs FileSystem) *Walker { - info, err := fs.Lstat(root) - return &Walker{ - fs: fs, - stack: []item{{root, info, err}}, - } -} - -// Step advances the Walker to the next file or directory, -// which will then be available through the Path, Stat, -// and Err methods. -// It returns false when the walk stops at the end of the tree. -func (w *Walker) Step() bool { - if w.descend && w.cur.err == nil && w.cur.info.IsDir() { - list, err := w.fs.ReadDir(w.cur.path) - if err != nil { - w.cur.err = err - w.stack = append(w.stack, w.cur) - } else { - for i := len(list) - 1; i >= 0; i-- { - path := w.fs.Join(w.cur.path, list[i].Name()) - w.stack = append(w.stack, item{path, list[i], nil}) - } - } - } - - if len(w.stack) == 0 { - return false - } - i := len(w.stack) - 1 - w.cur = w.stack[i] - w.stack = w.stack[:i] - w.descend = true - return true -} - -// Path returns the path to the most recent file or directory -// visited by a call to Step. It contains the argument to Walk -// as a prefix; that is, if Walk is called with "dir", which is -// a directory containing the file "a", Path will return "dir/a". -func (w *Walker) Path() string { - return w.cur.path -} - -// Stat returns info for the most recent file or directory -// visited by a call to Step. -func (w *Walker) Stat() os.FileInfo { - return w.cur.info -} - -// Err returns the error, if any, for the most recent attempt -// by Step to visit a file or directory. If a directory has -// an error, w will not descend into that directory. -func (w *Walker) Err() error { - return w.cur.err -} - -// SkipDir causes the currently visited directory to be skipped. -// If w is not on a directory, SkipDir has no effect. -func (w *Walker) SkipDir() { - w.descend = false -} diff --git a/vendor/github.com/magiconair/properties/CHANGELOG.md b/vendor/github.com/magiconair/properties/CHANGELOG.md index bf49a13..89ee938 100644 --- a/vendor/github.com/magiconair/properties/CHANGELOG.md +++ b/vendor/github.com/magiconair/properties/CHANGELOG.md @@ -1,5 +1,14 @@ ## Changelog +### Unreleased + + * [Issue #15](https://github.com/magiconair/properties/issues/15): Drop gocheck dependency + +### [1.7.1](https://github.com/magiconair/properties/tags/v1.7.1) - 13 Jan 2017 + + * [PR #16](https://github.com/magiconair/properties/pull/16): Keep gofmt happy + * [PR #18](https://github.com/magiconair/properties/pull/18): Fix Delete() function + ### [1.7.0](https://github.com/magiconair/properties/tags/v1.7.0) - 20 Mar 2016 * [Issue #10](https://github.com/magiconair/properties/issues/10): Add [LoadURL,LoadURLs,MustLoadURL,MustLoadURLs](http://godoc.org/github.com/magiconair/properties#Properties.LoadURL) method to load properties from a URL. diff --git a/vendor/github.com/magiconair/properties/README.md b/vendor/github.com/magiconair/properties/README.md index 1ae0035..5985911 100644 --- a/vendor/github.com/magiconair/properties/README.md +++ b/vendor/github.com/magiconair/properties/README.md @@ -1,7 +1,7 @@ Overview [![Build Status](https://travis-ci.org/magiconair/properties.svg?branch=master)](https://travis-ci.org/magiconair/properties) ======== -#### Current version: 1.7.0 +#### Current version: 1.7.1 properties is a Go library for reading and writing properties files. diff --git a/vendor/github.com/magiconair/properties/decode.go b/vendor/github.com/magiconair/properties/decode.go index b717a64..0a961bb 100644 --- a/vendor/github.com/magiconair/properties/decode.go +++ b/vendor/github.com/magiconair/properties/decode.go @@ -1,4 +1,4 @@ -// Copyright 2016 Frank Schroeder. All rights reserved. +// Copyright 2017 Frank Schroeder. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. @@ -158,16 +158,16 @@ func dec(p *Properties, key string, def *string, opts map[string]string, v refle // keydef returns the property key and the default value based on the // name of the struct field and the options in the tag. keydef := func(f reflect.StructField) (string, *string, map[string]string) { - key, opts := parseTag(f.Tag.Get("properties")) + _key, _opts := parseTag(f.Tag.Get("properties")) - var def *string - if d, ok := opts["default"]; ok { - def = &d + var _def *string + if d, ok := _opts["default"]; ok { + _def = &d } - if key != "" { - return key, def, opts + if _key != "" { + return _key, _def, _opts } - return f.Name, def, opts + return f.Name, _def, _opts } switch { @@ -223,7 +223,7 @@ func dec(p *Properties, key string, def *string, opts map[string]string, v refle case isMap(t): valT := t.Elem() m := reflect.MakeMap(t) - for postfix, _ := range p.FilterStripPrefix(key + ".").m { + for postfix := range p.FilterStripPrefix(key + ".").m { pp := strings.SplitN(postfix, ".", 2) mk, mv := pp[0], reflect.New(valT) if err := dec(p, key+"."+mk, nil, nil, mv); err != nil { @@ -274,7 +274,6 @@ func isArray(t reflect.Type) bool { return t.Kind() == reflect.Array || t.Kin func isBool(t reflect.Type) bool { return t.Kind() == reflect.Bool } func isDuration(t reflect.Type) bool { return t == reflect.TypeOf(time.Second) } func isMap(t reflect.Type) bool { return t.Kind() == reflect.Map } -func isNumeric(t reflect.Type) bool { return isInt(t) || isUint(t) || isFloat(t) } func isPtr(t reflect.Type) bool { return t.Kind() == reflect.Ptr } func isString(t reflect.Type) bool { return t.Kind() == reflect.String } func isStruct(t reflect.Type) bool { return t.Kind() == reflect.Struct } diff --git a/vendor/github.com/magiconair/properties/doc.go b/vendor/github.com/magiconair/properties/doc.go index ed1ff51..36c8368 100644 --- a/vendor/github.com/magiconair/properties/doc.go +++ b/vendor/github.com/magiconair/properties/doc.go @@ -1,4 +1,4 @@ -// Copyright 2016 Frank Schroeder. All rights reserved. +// Copyright 2017 Frank Schroeder. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. diff --git a/vendor/github.com/magiconair/properties/integrate.go b/vendor/github.com/magiconair/properties/integrate.go index 37baaad..0d775e0 100644 --- a/vendor/github.com/magiconair/properties/integrate.go +++ b/vendor/github.com/magiconair/properties/integrate.go @@ -1,4 +1,4 @@ -// Copyright 2016 Frank Schroeder. All rights reserved. +// Copyright 2017 Frank Schroeder. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. diff --git a/vendor/github.com/magiconair/properties/lex.go b/vendor/github.com/magiconair/properties/lex.go index 014e63f..a3cba03 100644 --- a/vendor/github.com/magiconair/properties/lex.go +++ b/vendor/github.com/magiconair/properties/lex.go @@ -1,4 +1,4 @@ -// Copyright 2016 Frank Schroeder. All rights reserved. +// Copyright 2017 Frank Schroeder. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // @@ -72,7 +72,7 @@ type lexer struct { // next returns the next rune in the input. func (l *lexer) next() rune { - if int(l.pos) >= len(l.input) { + if l.pos >= len(l.input) { l.width = 0 return eof } @@ -96,8 +96,8 @@ func (l *lexer) backup() { // emit passes an item back to the client. func (l *lexer) emit(t itemType) { - item := item{t, l.start, string(l.runes)} - l.items <- item + i := item{t, l.start, string(l.runes)} + l.items <- i l.start = l.pos l.runes = l.runes[:0] } @@ -114,7 +114,7 @@ func (l *lexer) appendRune(r rune) { // accept consumes the next rune if it's from the valid set. func (l *lexer) accept(valid string) bool { - if strings.IndexRune(valid, l.next()) >= 0 { + if strings.ContainsRune(valid, l.next()) { return true } l.backup() @@ -123,7 +123,7 @@ func (l *lexer) accept(valid string) bool { // acceptRun consumes a run of runes from the valid set. func (l *lexer) acceptRun(valid string) { - for strings.IndexRune(valid, l.next()) >= 0 { + for strings.ContainsRune(valid, l.next()) { } l.backup() } @@ -156,9 +156,9 @@ func (l *lexer) errorf(format string, args ...interface{}) stateFn { // nextItem returns the next item from the input. func (l *lexer) nextItem() item { - item := <-l.items - l.lastPos = item.pos - return item + i := <-l.items + l.lastPos = i.pos + return i } // lex creates a new scanner for the input string. @@ -279,8 +279,7 @@ func lexValue(l *lexer) stateFn { for { switch r := l.next(); { case isEscape(r): - r := l.peek() - if isEOL(r) { + if isEOL(l.peek()) { l.next() l.acceptRun(whitespace) } else { diff --git a/vendor/github.com/magiconair/properties/load.go b/vendor/github.com/magiconair/properties/load.go index 4300fec..701a86d 100644 --- a/vendor/github.com/magiconair/properties/load.go +++ b/vendor/github.com/magiconair/properties/load.go @@ -1,4 +1,4 @@ -// Copyright 2016 Frank Schroeder. All rights reserved. +// Copyright 2017 Frank Schroeder. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. @@ -98,7 +98,7 @@ func MustLoadURL(url string) *Properties { return must(LoadURL(url)) } -// MustLoadFiles reads the content of multiple URLs in the given order into a +// MustLoadURLs reads the content of multiple URLs in the given order into a // Properties struct and panics on error. If 'ignoreMissing' is true then a 404 // status code will not be reported as error. func MustLoadURLs(urls []string, ignoreMissing bool) *Properties { @@ -172,10 +172,12 @@ func loadURL(url string, ignoreMissing bool) (*Properties, error) { return nil, fmt.Errorf("properties: %s returned %d", url, resp.StatusCode) } body, err := ioutil.ReadAll(resp.Body) - resp.Body.Close() if err != nil { return nil, fmt.Errorf("properties: %s error reading response. %s", url, err) } + if err = resp.Body.Close(); err != nil { + return nil, fmt.Errorf("properties: %s error reading response. %s", url, err) + } ct := resp.Header.Get("Content-Type") var enc Encoding diff --git a/vendor/github.com/magiconair/properties/parser.go b/vendor/github.com/magiconair/properties/parser.go index ff0e1e1..90f555c 100644 --- a/vendor/github.com/magiconair/properties/parser.go +++ b/vendor/github.com/magiconair/properties/parser.go @@ -1,4 +1,4 @@ -// Copyright 2016 Frank Schroeder. All rights reserved. +// Copyright 2017 Frank Schroeder. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. diff --git a/vendor/github.com/magiconair/properties/properties.go b/vendor/github.com/magiconair/properties/properties.go index e7e0104..80360c9 100644 --- a/vendor/github.com/magiconair/properties/properties.go +++ b/vendor/github.com/magiconair/properties/properties.go @@ -1,4 +1,4 @@ -// Copyright 2016 Frank Schroeder. All rights reserved. +// Copyright 2017 Frank Schroeder. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. @@ -28,8 +28,10 @@ type ErrorHandlerFunc func(error) // functions. The default is LogFatalHandler. var ErrorHandler ErrorHandlerFunc = LogFatalHandler +// LogHandlerFunc defines the function prototype for logging errors. type LogHandlerFunc func(fmt string, args ...interface{}) +// LogPrintf defines a log handler which uses log.Printf. var LogPrintf LogHandlerFunc = log.Printf // LogFatalHandler handles the error by logging a fatal error and exiting. @@ -444,6 +446,8 @@ func (p *Properties) FilterRegexp(re *regexp.Regexp) *Properties { pp := NewProperties() for _, k := range p.k { if re.MatchString(k) { + // TODO(fs): we are ignoring the error which flags a circular reference. + // TODO(fs): since we are just copying a subset of keys this cannot happen (fingers crossed) pp.Set(k, p.m[k]) } } @@ -456,6 +460,8 @@ func (p *Properties) FilterPrefix(prefix string) *Properties { pp := NewProperties() for _, k := range p.k { if strings.HasPrefix(k, prefix) { + // TODO(fs): we are ignoring the error which flags a circular reference. + // TODO(fs): since we are just copying a subset of keys this cannot happen (fingers crossed) pp.Set(k, p.m[k]) } } @@ -469,6 +475,9 @@ func (p *Properties) FilterStripPrefix(prefix string) *Properties { n := len(prefix) for _, k := range p.k { if len(k) > len(prefix) && strings.HasPrefix(k, prefix) { + // TODO(fs): we are ignoring the error which flags a circular reference. + // TODO(fs): since we are modifying keys I am not entirely sure whether we can create a circular reference + // TODO(fs): this function should probably return an error but the signature is fixed pp.Set(k[n:], p.m[k]) } } @@ -483,9 +492,7 @@ func (p *Properties) Len() int { // Keys returns all keys in the same order as in the input. func (p *Properties) Keys() []string { keys := make([]string, len(p.k)) - for i, k := range p.k { - keys[i] = k - } + copy(keys, p.k) return keys } @@ -624,7 +631,7 @@ func (p *Properties) Delete(key string) { newKeys := []string{} for _, k := range p.k { if k != key { - newKeys = append(newKeys, key) + newKeys = append(newKeys, k) } } p.k = newKeys @@ -632,14 +639,14 @@ func (p *Properties) Delete(key string) { // Merge merges properties, comments and keys from other *Properties into p func (p *Properties) Merge(other *Properties) { - for k,v := range other.m { + for k, v := range other.m { p.m[k] = v } - for k,v := range other.c { + for k, v := range other.c { p.c[k] = v } - outer: +outer: for _, otherKey := range other.k { for _, key := range p.k { if otherKey == key { diff --git a/vendor/github.com/magiconair/properties/rangecheck.go b/vendor/github.com/magiconair/properties/rangecheck.go index d9ce280..2e907d5 100644 --- a/vendor/github.com/magiconair/properties/rangecheck.go +++ b/vendor/github.com/magiconair/properties/rangecheck.go @@ -1,4 +1,4 @@ -// Copyright 2016 Frank Schroeder. All rights reserved. +// Copyright 2017 Frank Schroeder. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. diff --git a/vendor/github.com/mattn/go-colorable/LICENSE b/vendor/github.com/mattn/go-colorable/LICENSE new file mode 100644 index 0000000..91b5cef --- /dev/null +++ b/vendor/github.com/mattn/go-colorable/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2016 Yasuhiro Matsumoto + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/vendor/github.com/mattn/go-colorable/README.md b/vendor/github.com/mattn/go-colorable/README.md new file mode 100644 index 0000000..e84226a --- /dev/null +++ b/vendor/github.com/mattn/go-colorable/README.md @@ -0,0 +1,43 @@ +# go-colorable + +Colorable writer for windows. + +For example, most of logger packages doesn't show colors on windows. (I know we can do it with ansicon. But I don't want.) +This package is possible to handle escape sequence for ansi color on windows. + +## Too Bad! + +![](https://raw.githubusercontent.com/mattn/go-colorable/gh-pages/bad.png) + + +## So Good! + +![](https://raw.githubusercontent.com/mattn/go-colorable/gh-pages/good.png) + +## Usage + +```go +logrus.SetFormatter(&logrus.TextFormatter{ForceColors: true}) +logrus.SetOutput(colorable.NewColorableStdout()) + +logrus.Info("succeeded") +logrus.Warn("not correct") +logrus.Error("something error") +logrus.Fatal("panic") +``` + +You can compile above code on non-windows OSs. + +## Installation + +``` +$ go get github.com/mattn/go-colorable +``` + +# License + +MIT + +# Author + +Yasuhiro Matsumoto (a.k.a mattn) diff --git a/vendor/github.com/mattn/go-colorable/colorable_others.go b/vendor/github.com/mattn/go-colorable/colorable_others.go new file mode 100644 index 0000000..a7fe19a --- /dev/null +++ b/vendor/github.com/mattn/go-colorable/colorable_others.go @@ -0,0 +1,27 @@ +// +build !windows + +package colorable + +import ( + "io" + "os" +) + +// NewColorable return new instance of Writer which handle escape sequence. +func NewColorable(file *os.File) io.Writer { + if file == nil { + panic("nil passed instead of *os.File to NewColorable()") + } + + return file +} + +// NewColorableStdout return new instance of Writer which handle escape sequence for stdout. +func NewColorableStdout() io.Writer { + return os.Stdout +} + +// NewColorableStderr return new instance of Writer which handle escape sequence for stderr. +func NewColorableStderr() io.Writer { + return os.Stderr +} diff --git a/vendor/github.com/mattn/go-colorable/colorable_windows.go b/vendor/github.com/mattn/go-colorable/colorable_windows.go new file mode 100644 index 0000000..628ad90 --- /dev/null +++ b/vendor/github.com/mattn/go-colorable/colorable_windows.go @@ -0,0 +1,820 @@ +package colorable + +import ( + "bytes" + "io" + "math" + "os" + "strconv" + "strings" + "syscall" + "unsafe" + + "github.com/mattn/go-isatty" +) + +const ( + foregroundBlue = 0x1 + foregroundGreen = 0x2 + foregroundRed = 0x4 + foregroundIntensity = 0x8 + foregroundMask = (foregroundRed | foregroundBlue | foregroundGreen | foregroundIntensity) + backgroundBlue = 0x10 + backgroundGreen = 0x20 + backgroundRed = 0x40 + backgroundIntensity = 0x80 + backgroundMask = (backgroundRed | backgroundBlue | backgroundGreen | backgroundIntensity) +) + +type wchar uint16 +type short int16 +type dword uint32 +type word uint16 + +type coord struct { + x short + y short +} + +type smallRect struct { + left short + top short + right short + bottom short +} + +type consoleScreenBufferInfo struct { + size coord + cursorPosition coord + attributes word + window smallRect + maximumWindowSize coord +} + +type consoleCursorInfo struct { + size dword + visible int32 +} + +var ( + kernel32 = syscall.NewLazyDLL("kernel32.dll") + procGetConsoleScreenBufferInfo = kernel32.NewProc("GetConsoleScreenBufferInfo") + procSetConsoleTextAttribute = kernel32.NewProc("SetConsoleTextAttribute") + procSetConsoleCursorPosition = kernel32.NewProc("SetConsoleCursorPosition") + procFillConsoleOutputCharacter = kernel32.NewProc("FillConsoleOutputCharacterW") + procFillConsoleOutputAttribute = kernel32.NewProc("FillConsoleOutputAttribute") + procGetConsoleCursorInfo = kernel32.NewProc("GetConsoleCursorInfo") + procSetConsoleCursorInfo = kernel32.NewProc("SetConsoleCursorInfo") +) + +type Writer struct { + out io.Writer + handle syscall.Handle + lastbuf bytes.Buffer + oldattr word + oldpos coord +} + +// NewColorable return new instance of Writer which handle escape sequence from File. +func NewColorable(file *os.File) io.Writer { + if file == nil { + panic("nil passed instead of *os.File to NewColorable()") + } + + if isatty.IsTerminal(file.Fd()) { + var csbi consoleScreenBufferInfo + handle := syscall.Handle(file.Fd()) + procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) + return &Writer{out: file, handle: handle, oldattr: csbi.attributes, oldpos: coord{0, 0}} + } else { + return file + } +} + +// NewColorableStdout return new instance of Writer which handle escape sequence for stdout. +func NewColorableStdout() io.Writer { + return NewColorable(os.Stdout) +} + +// NewColorableStderr return new instance of Writer which handle escape sequence for stderr. +func NewColorableStderr() io.Writer { + return NewColorable(os.Stderr) +} + +var color256 = map[int]int{ + 0: 0x000000, + 1: 0x800000, + 2: 0x008000, + 3: 0x808000, + 4: 0x000080, + 5: 0x800080, + 6: 0x008080, + 7: 0xc0c0c0, + 8: 0x808080, + 9: 0xff0000, + 10: 0x00ff00, + 11: 0xffff00, + 12: 0x0000ff, + 13: 0xff00ff, + 14: 0x00ffff, + 15: 0xffffff, + 16: 0x000000, + 17: 0x00005f, + 18: 0x000087, + 19: 0x0000af, + 20: 0x0000d7, + 21: 0x0000ff, + 22: 0x005f00, + 23: 0x005f5f, + 24: 0x005f87, + 25: 0x005faf, + 26: 0x005fd7, + 27: 0x005fff, + 28: 0x008700, + 29: 0x00875f, + 30: 0x008787, + 31: 0x0087af, + 32: 0x0087d7, + 33: 0x0087ff, + 34: 0x00af00, + 35: 0x00af5f, + 36: 0x00af87, + 37: 0x00afaf, + 38: 0x00afd7, + 39: 0x00afff, + 40: 0x00d700, + 41: 0x00d75f, + 42: 0x00d787, + 43: 0x00d7af, + 44: 0x00d7d7, + 45: 0x00d7ff, + 46: 0x00ff00, + 47: 0x00ff5f, + 48: 0x00ff87, + 49: 0x00ffaf, + 50: 0x00ffd7, + 51: 0x00ffff, + 52: 0x5f0000, + 53: 0x5f005f, + 54: 0x5f0087, + 55: 0x5f00af, + 56: 0x5f00d7, + 57: 0x5f00ff, + 58: 0x5f5f00, + 59: 0x5f5f5f, + 60: 0x5f5f87, + 61: 0x5f5faf, + 62: 0x5f5fd7, + 63: 0x5f5fff, + 64: 0x5f8700, + 65: 0x5f875f, + 66: 0x5f8787, + 67: 0x5f87af, + 68: 0x5f87d7, + 69: 0x5f87ff, + 70: 0x5faf00, + 71: 0x5faf5f, + 72: 0x5faf87, + 73: 0x5fafaf, + 74: 0x5fafd7, + 75: 0x5fafff, + 76: 0x5fd700, + 77: 0x5fd75f, + 78: 0x5fd787, + 79: 0x5fd7af, + 80: 0x5fd7d7, + 81: 0x5fd7ff, + 82: 0x5fff00, + 83: 0x5fff5f, + 84: 0x5fff87, + 85: 0x5fffaf, + 86: 0x5fffd7, + 87: 0x5fffff, + 88: 0x870000, + 89: 0x87005f, + 90: 0x870087, + 91: 0x8700af, + 92: 0x8700d7, + 93: 0x8700ff, + 94: 0x875f00, + 95: 0x875f5f, + 96: 0x875f87, + 97: 0x875faf, + 98: 0x875fd7, + 99: 0x875fff, + 100: 0x878700, + 101: 0x87875f, + 102: 0x878787, + 103: 0x8787af, + 104: 0x8787d7, + 105: 0x8787ff, + 106: 0x87af00, + 107: 0x87af5f, + 108: 0x87af87, + 109: 0x87afaf, + 110: 0x87afd7, + 111: 0x87afff, + 112: 0x87d700, + 113: 0x87d75f, + 114: 0x87d787, + 115: 0x87d7af, + 116: 0x87d7d7, + 117: 0x87d7ff, + 118: 0x87ff00, + 119: 0x87ff5f, + 120: 0x87ff87, + 121: 0x87ffaf, + 122: 0x87ffd7, + 123: 0x87ffff, + 124: 0xaf0000, + 125: 0xaf005f, + 126: 0xaf0087, + 127: 0xaf00af, + 128: 0xaf00d7, + 129: 0xaf00ff, + 130: 0xaf5f00, + 131: 0xaf5f5f, + 132: 0xaf5f87, + 133: 0xaf5faf, + 134: 0xaf5fd7, + 135: 0xaf5fff, + 136: 0xaf8700, + 137: 0xaf875f, + 138: 0xaf8787, + 139: 0xaf87af, + 140: 0xaf87d7, + 141: 0xaf87ff, + 142: 0xafaf00, + 143: 0xafaf5f, + 144: 0xafaf87, + 145: 0xafafaf, + 146: 0xafafd7, + 147: 0xafafff, + 148: 0xafd700, + 149: 0xafd75f, + 150: 0xafd787, + 151: 0xafd7af, + 152: 0xafd7d7, + 153: 0xafd7ff, + 154: 0xafff00, + 155: 0xafff5f, + 156: 0xafff87, + 157: 0xafffaf, + 158: 0xafffd7, + 159: 0xafffff, + 160: 0xd70000, + 161: 0xd7005f, + 162: 0xd70087, + 163: 0xd700af, + 164: 0xd700d7, + 165: 0xd700ff, + 166: 0xd75f00, + 167: 0xd75f5f, + 168: 0xd75f87, + 169: 0xd75faf, + 170: 0xd75fd7, + 171: 0xd75fff, + 172: 0xd78700, + 173: 0xd7875f, + 174: 0xd78787, + 175: 0xd787af, + 176: 0xd787d7, + 177: 0xd787ff, + 178: 0xd7af00, + 179: 0xd7af5f, + 180: 0xd7af87, + 181: 0xd7afaf, + 182: 0xd7afd7, + 183: 0xd7afff, + 184: 0xd7d700, + 185: 0xd7d75f, + 186: 0xd7d787, + 187: 0xd7d7af, + 188: 0xd7d7d7, + 189: 0xd7d7ff, + 190: 0xd7ff00, + 191: 0xd7ff5f, + 192: 0xd7ff87, + 193: 0xd7ffaf, + 194: 0xd7ffd7, + 195: 0xd7ffff, + 196: 0xff0000, + 197: 0xff005f, + 198: 0xff0087, + 199: 0xff00af, + 200: 0xff00d7, + 201: 0xff00ff, + 202: 0xff5f00, + 203: 0xff5f5f, + 204: 0xff5f87, + 205: 0xff5faf, + 206: 0xff5fd7, + 207: 0xff5fff, + 208: 0xff8700, + 209: 0xff875f, + 210: 0xff8787, + 211: 0xff87af, + 212: 0xff87d7, + 213: 0xff87ff, + 214: 0xffaf00, + 215: 0xffaf5f, + 216: 0xffaf87, + 217: 0xffafaf, + 218: 0xffafd7, + 219: 0xffafff, + 220: 0xffd700, + 221: 0xffd75f, + 222: 0xffd787, + 223: 0xffd7af, + 224: 0xffd7d7, + 225: 0xffd7ff, + 226: 0xffff00, + 227: 0xffff5f, + 228: 0xffff87, + 229: 0xffffaf, + 230: 0xffffd7, + 231: 0xffffff, + 232: 0x080808, + 233: 0x121212, + 234: 0x1c1c1c, + 235: 0x262626, + 236: 0x303030, + 237: 0x3a3a3a, + 238: 0x444444, + 239: 0x4e4e4e, + 240: 0x585858, + 241: 0x626262, + 242: 0x6c6c6c, + 243: 0x767676, + 244: 0x808080, + 245: 0x8a8a8a, + 246: 0x949494, + 247: 0x9e9e9e, + 248: 0xa8a8a8, + 249: 0xb2b2b2, + 250: 0xbcbcbc, + 251: 0xc6c6c6, + 252: 0xd0d0d0, + 253: 0xdadada, + 254: 0xe4e4e4, + 255: 0xeeeeee, +} + +// Write write data on console +func (w *Writer) Write(data []byte) (n int, err error) { + var csbi consoleScreenBufferInfo + procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) + + er := bytes.NewReader(data) + var bw [1]byte +loop: + for { + r1, _, err := procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) + if r1 == 0 { + break loop + } + + c1, err := er.ReadByte() + if err != nil { + break loop + } + if c1 != 0x1b { + bw[0] = c1 + w.out.Write(bw[:]) + continue + } + c2, err := er.ReadByte() + if err != nil { + w.lastbuf.WriteByte(c1) + break loop + } + if c2 != 0x5b { + w.lastbuf.WriteByte(c1) + w.lastbuf.WriteByte(c2) + continue + } + + var buf bytes.Buffer + var m byte + for { + c, err := er.ReadByte() + if err != nil { + w.lastbuf.WriteByte(c1) + w.lastbuf.WriteByte(c2) + w.lastbuf.Write(buf.Bytes()) + break loop + } + if ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || c == '@' { + m = c + break + } + buf.Write([]byte(string(c))) + } + + var csbi consoleScreenBufferInfo + switch m { + case 'A': + n, err = strconv.Atoi(buf.String()) + if err != nil { + continue + } + procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) + csbi.cursorPosition.y -= short(n) + procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) + case 'B': + n, err = strconv.Atoi(buf.String()) + if err != nil { + continue + } + procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) + csbi.cursorPosition.y += short(n) + procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) + case 'C': + n, err = strconv.Atoi(buf.String()) + if err != nil { + continue + } + procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) + csbi.cursorPosition.x -= short(n) + procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) + case 'D': + n, err = strconv.Atoi(buf.String()) + if err != nil { + continue + } + if n, err = strconv.Atoi(buf.String()); err == nil { + var csbi consoleScreenBufferInfo + procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) + csbi.cursorPosition.x += short(n) + procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) + } + case 'E': + n, err = strconv.Atoi(buf.String()) + if err != nil { + continue + } + procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) + csbi.cursorPosition.x = 0 + csbi.cursorPosition.y += short(n) + procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) + case 'F': + n, err = strconv.Atoi(buf.String()) + if err != nil { + continue + } + procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) + csbi.cursorPosition.x = 0 + csbi.cursorPosition.y -= short(n) + procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) + case 'G': + n, err = strconv.Atoi(buf.String()) + if err != nil { + continue + } + procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) + csbi.cursorPosition.x = short(n - 1) + procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) + case 'H': + token := strings.Split(buf.String(), ";") + if len(token) != 2 { + continue + } + n1, err := strconv.Atoi(token[0]) + if err != nil { + continue + } + n2, err := strconv.Atoi(token[1]) + if err != nil { + continue + } + csbi.cursorPosition.x = short(n2 - 1) + csbi.cursorPosition.y = short(n1 - 1) + procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) + case 'J': + n, err := strconv.Atoi(buf.String()) + if err != nil { + continue + } + procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) + var cursor coord + switch n { + case 0: + cursor = coord{x: csbi.cursorPosition.x, y: csbi.cursorPosition.y} + case 1: + cursor = coord{x: csbi.window.left, y: csbi.window.top} + case 2: + cursor = coord{x: csbi.window.left, y: csbi.window.top} + } + var count, written dword + count = dword(csbi.size.x - csbi.cursorPosition.x + (csbi.size.y-csbi.cursorPosition.y)*csbi.size.x) + procFillConsoleOutputCharacter.Call(uintptr(w.handle), uintptr(' '), uintptr(count), *(*uintptr)(unsafe.Pointer(&cursor)), uintptr(unsafe.Pointer(&written))) + procFillConsoleOutputAttribute.Call(uintptr(w.handle), uintptr(csbi.attributes), uintptr(count), *(*uintptr)(unsafe.Pointer(&cursor)), uintptr(unsafe.Pointer(&written))) + case 'K': + n, err := strconv.Atoi(buf.String()) + if err != nil { + continue + } + procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) + var cursor coord + switch n { + case 0: + cursor = coord{x: csbi.cursorPosition.x, y: csbi.cursorPosition.y} + case 1: + cursor = coord{x: csbi.window.left, y: csbi.window.top + csbi.cursorPosition.y} + case 2: + cursor = coord{x: csbi.window.left, y: csbi.window.top + csbi.cursorPosition.y} + } + var count, written dword + count = dword(csbi.size.x - csbi.cursorPosition.x) + procFillConsoleOutputCharacter.Call(uintptr(w.handle), uintptr(' '), uintptr(count), *(*uintptr)(unsafe.Pointer(&cursor)), uintptr(unsafe.Pointer(&written))) + procFillConsoleOutputAttribute.Call(uintptr(w.handle), uintptr(csbi.attributes), uintptr(count), *(*uintptr)(unsafe.Pointer(&cursor)), uintptr(unsafe.Pointer(&written))) + case 'm': + procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) + attr := csbi.attributes + cs := buf.String() + if cs == "" { + procSetConsoleTextAttribute.Call(uintptr(w.handle), uintptr(w.oldattr)) + continue + } + token := strings.Split(cs, ";") + for i := 0; i < len(token); i++ { + ns := token[i] + if n, err = strconv.Atoi(ns); err == nil { + switch { + case n == 0 || n == 100: + attr = w.oldattr + case 1 <= n && n <= 5: + attr |= foregroundIntensity + case n == 7: + attr = ((attr & foregroundMask) << 4) | ((attr & backgroundMask) >> 4) + case 22 == n || n == 25 || n == 25: + attr |= foregroundIntensity + case n == 27: + attr = ((attr & foregroundMask) << 4) | ((attr & backgroundMask) >> 4) + case 30 <= n && n <= 37: + attr &= backgroundMask + if (n-30)&1 != 0 { + attr |= foregroundRed + } + if (n-30)&2 != 0 { + attr |= foregroundGreen + } + if (n-30)&4 != 0 { + attr |= foregroundBlue + } + case n == 38: // set foreground color. + if i < len(token)-2 && (token[i+1] == "5" || token[i+1] == "05") { + if n256, err := strconv.Atoi(token[i+2]); err == nil { + if n256foreAttr == nil { + n256setup() + } + attr &= backgroundMask + attr |= n256foreAttr[n256] + i += 2 + } + } else { + attr = attr & (w.oldattr & backgroundMask) + } + case n == 39: // reset foreground color. + attr &= backgroundMask + attr |= w.oldattr & foregroundMask + case 40 <= n && n <= 47: + attr &= foregroundMask + if (n-40)&1 != 0 { + attr |= backgroundRed + } + if (n-40)&2 != 0 { + attr |= backgroundGreen + } + if (n-40)&4 != 0 { + attr |= backgroundBlue + } + case n == 48: // set background color. + if i < len(token)-2 && token[i+1] == "5" { + if n256, err := strconv.Atoi(token[i+2]); err == nil { + if n256backAttr == nil { + n256setup() + } + attr &= foregroundMask + attr |= n256backAttr[n256] + i += 2 + } + } else { + attr = attr & (w.oldattr & foregroundMask) + } + case n == 49: // reset foreground color. + attr &= foregroundMask + attr |= w.oldattr & backgroundMask + case 90 <= n && n <= 97: + attr = (attr & backgroundMask) + attr |= foregroundIntensity + if (n-90)&1 != 0 { + attr |= foregroundRed + } + if (n-90)&2 != 0 { + attr |= foregroundGreen + } + if (n-90)&4 != 0 { + attr |= foregroundBlue + } + case 100 <= n && n <= 107: + attr = (attr & foregroundMask) + attr |= backgroundIntensity + if (n-100)&1 != 0 { + attr |= backgroundRed + } + if (n-100)&2 != 0 { + attr |= backgroundGreen + } + if (n-100)&4 != 0 { + attr |= backgroundBlue + } + } + procSetConsoleTextAttribute.Call(uintptr(w.handle), uintptr(attr)) + } + } + case 'h': + cs := buf.String() + if cs == "?25" { + var ci consoleCursorInfo + procGetConsoleCursorInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&ci))) + ci.visible = 1 + procSetConsoleCursorInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&ci))) + } + case 'l': + cs := buf.String() + if cs == "?25" { + var ci consoleCursorInfo + procGetConsoleCursorInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&ci))) + ci.visible = 0 + procSetConsoleCursorInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&ci))) + } + case 's': + procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) + w.oldpos = csbi.cursorPosition + case 'u': + procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&w.oldpos))) + } + } + return len(data) - w.lastbuf.Len(), nil +} + +type consoleColor struct { + rgb int + red bool + green bool + blue bool + intensity bool +} + +func (c consoleColor) foregroundAttr() (attr word) { + if c.red { + attr |= foregroundRed + } + if c.green { + attr |= foregroundGreen + } + if c.blue { + attr |= foregroundBlue + } + if c.intensity { + attr |= foregroundIntensity + } + return +} + +func (c consoleColor) backgroundAttr() (attr word) { + if c.red { + attr |= backgroundRed + } + if c.green { + attr |= backgroundGreen + } + if c.blue { + attr |= backgroundBlue + } + if c.intensity { + attr |= backgroundIntensity + } + return +} + +var color16 = []consoleColor{ + consoleColor{0x000000, false, false, false, false}, + consoleColor{0x000080, false, false, true, false}, + consoleColor{0x008000, false, true, false, false}, + consoleColor{0x008080, false, true, true, false}, + consoleColor{0x800000, true, false, false, false}, + consoleColor{0x800080, true, false, true, false}, + consoleColor{0x808000, true, true, false, false}, + consoleColor{0xc0c0c0, true, true, true, false}, + consoleColor{0x808080, false, false, false, true}, + consoleColor{0x0000ff, false, false, true, true}, + consoleColor{0x00ff00, false, true, false, true}, + consoleColor{0x00ffff, false, true, true, true}, + consoleColor{0xff0000, true, false, false, true}, + consoleColor{0xff00ff, true, false, true, true}, + consoleColor{0xffff00, true, true, false, true}, + consoleColor{0xffffff, true, true, true, true}, +} + +type hsv struct { + h, s, v float32 +} + +func (a hsv) dist(b hsv) float32 { + dh := a.h - b.h + switch { + case dh > 0.5: + dh = 1 - dh + case dh < -0.5: + dh = -1 - dh + } + ds := a.s - b.s + dv := a.v - b.v + return float32(math.Sqrt(float64(dh*dh + ds*ds + dv*dv))) +} + +func toHSV(rgb int) hsv { + r, g, b := float32((rgb&0xFF0000)>>16)/256.0, + float32((rgb&0x00FF00)>>8)/256.0, + float32(rgb&0x0000FF)/256.0 + min, max := minmax3f(r, g, b) + h := max - min + if h > 0 { + if max == r { + h = (g - b) / h + if h < 0 { + h += 6 + } + } else if max == g { + h = 2 + (b-r)/h + } else { + h = 4 + (r-g)/h + } + } + h /= 6.0 + s := max - min + if max != 0 { + s /= max + } + v := max + return hsv{h: h, s: s, v: v} +} + +type hsvTable []hsv + +func toHSVTable(rgbTable []consoleColor) hsvTable { + t := make(hsvTable, len(rgbTable)) + for i, c := range rgbTable { + t[i] = toHSV(c.rgb) + } + return t +} + +func (t hsvTable) find(rgb int) consoleColor { + hsv := toHSV(rgb) + n := 7 + l := float32(5.0) + for i, p := range t { + d := hsv.dist(p) + if d < l { + l, n = d, i + } + } + return color16[n] +} + +func minmax3f(a, b, c float32) (min, max float32) { + if a < b { + if b < c { + return a, c + } else if a < c { + return a, b + } else { + return c, b + } + } else { + if a < c { + return b, c + } else if b < c { + return b, a + } else { + return c, a + } + } +} + +var n256foreAttr []word +var n256backAttr []word + +func n256setup() { + n256foreAttr = make([]word, 256) + n256backAttr = make([]word, 256) + t := toHSVTable(color16) + for i, rgb := range color256 { + c := t.find(rgb) + n256foreAttr[i] = c.foregroundAttr() + n256backAttr[i] = c.backgroundAttr() + } +} diff --git a/vendor/github.com/mattn/go-colorable/noncolorable.go b/vendor/github.com/mattn/go-colorable/noncolorable.go new file mode 100644 index 0000000..ca588c7 --- /dev/null +++ b/vendor/github.com/mattn/go-colorable/noncolorable.go @@ -0,0 +1,61 @@ +package colorable + +import ( + "bytes" + "io" +) + +// NonColorable hold writer but remove escape sequence. +type NonColorable struct { + out io.Writer + lastbuf bytes.Buffer +} + +// NewNonColorable return new instance of Writer which remove escape sequence from Writer. +func NewNonColorable(w io.Writer) io.Writer { + return &NonColorable{out: w} +} + +// Write write data on console +func (w *NonColorable) Write(data []byte) (n int, err error) { + er := bytes.NewReader(data) + var bw [1]byte +loop: + for { + c1, err := er.ReadByte() + if err != nil { + break loop + } + if c1 != 0x1b { + bw[0] = c1 + w.out.Write(bw[:]) + continue + } + c2, err := er.ReadByte() + if err != nil { + w.lastbuf.WriteByte(c1) + break loop + } + if c2 != 0x5b { + w.lastbuf.WriteByte(c1) + w.lastbuf.WriteByte(c2) + continue + } + + var buf bytes.Buffer + for { + c, err := er.ReadByte() + if err != nil { + w.lastbuf.WriteByte(c1) + w.lastbuf.WriteByte(c2) + w.lastbuf.Write(buf.Bytes()) + break loop + } + if ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || c == '@' { + break + } + buf.Write([]byte(string(c))) + } + } + return len(data) - w.lastbuf.Len(), nil +} diff --git a/vendor/github.com/mattn/go-isatty/LICENSE b/vendor/github.com/mattn/go-isatty/LICENSE new file mode 100644 index 0000000..65dc692 --- /dev/null +++ b/vendor/github.com/mattn/go-isatty/LICENSE @@ -0,0 +1,9 @@ +Copyright (c) Yasuhiro MATSUMOTO + +MIT License (Expat) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/github.com/mattn/go-isatty/README.md b/vendor/github.com/mattn/go-isatty/README.md new file mode 100644 index 0000000..74845de --- /dev/null +++ b/vendor/github.com/mattn/go-isatty/README.md @@ -0,0 +1,37 @@ +# go-isatty + +isatty for golang + +## Usage + +```go +package main + +import ( + "fmt" + "github.com/mattn/go-isatty" + "os" +) + +func main() { + if isatty.IsTerminal(os.Stdout.Fd()) { + fmt.Println("Is Terminal") + } else { + fmt.Println("Is Not Terminal") + } +} +``` + +## Installation + +``` +$ go get github.com/mattn/go-isatty +``` + +# License + +MIT + +# Author + +Yasuhiro Matsumoto (a.k.a mattn) diff --git a/vendor/github.com/mattn/go-isatty/doc.go b/vendor/github.com/mattn/go-isatty/doc.go new file mode 100644 index 0000000..17d4f90 --- /dev/null +++ b/vendor/github.com/mattn/go-isatty/doc.go @@ -0,0 +1,2 @@ +// Package isatty implements interface to isatty +package isatty diff --git a/vendor/github.com/mattn/go-isatty/isatty_appengine.go b/vendor/github.com/mattn/go-isatty/isatty_appengine.go new file mode 100644 index 0000000..83c5887 --- /dev/null +++ b/vendor/github.com/mattn/go-isatty/isatty_appengine.go @@ -0,0 +1,9 @@ +// +build appengine + +package isatty + +// IsTerminal returns true if the file descriptor is terminal which +// is always false on on appengine classic which is a sandboxed PaaS. +func IsTerminal(fd uintptr) bool { + return false +} diff --git a/vendor/github.com/mattn/go-isatty/isatty_bsd.go b/vendor/github.com/mattn/go-isatty/isatty_bsd.go new file mode 100644 index 0000000..42f2514 --- /dev/null +++ b/vendor/github.com/mattn/go-isatty/isatty_bsd.go @@ -0,0 +1,18 @@ +// +build darwin freebsd openbsd netbsd dragonfly +// +build !appengine + +package isatty + +import ( + "syscall" + "unsafe" +) + +const ioctlReadTermios = syscall.TIOCGETA + +// IsTerminal return true if the file descriptor is terminal. +func IsTerminal(fd uintptr) bool { + var termios syscall.Termios + _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, fd, ioctlReadTermios, uintptr(unsafe.Pointer(&termios)), 0, 0, 0) + return err == 0 +} diff --git a/vendor/github.com/mattn/go-isatty/isatty_linux.go b/vendor/github.com/mattn/go-isatty/isatty_linux.go new file mode 100644 index 0000000..9d24bac --- /dev/null +++ b/vendor/github.com/mattn/go-isatty/isatty_linux.go @@ -0,0 +1,18 @@ +// +build linux +// +build !appengine + +package isatty + +import ( + "syscall" + "unsafe" +) + +const ioctlReadTermios = syscall.TCGETS + +// IsTerminal return true if the file descriptor is terminal. +func IsTerminal(fd uintptr) bool { + var termios syscall.Termios + _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, fd, ioctlReadTermios, uintptr(unsafe.Pointer(&termios)), 0, 0, 0) + return err == 0 +} diff --git a/vendor/github.com/mattn/go-isatty/isatty_solaris.go b/vendor/github.com/mattn/go-isatty/isatty_solaris.go new file mode 100644 index 0000000..1f0c6bf --- /dev/null +++ b/vendor/github.com/mattn/go-isatty/isatty_solaris.go @@ -0,0 +1,16 @@ +// +build solaris +// +build !appengine + +package isatty + +import ( + "golang.org/x/sys/unix" +) + +// IsTerminal returns true if the given file descriptor is a terminal. +// see: http://src.illumos.org/source/xref/illumos-gate/usr/src/lib/libbc/libc/gen/common/isatty.c +func IsTerminal(fd uintptr) bool { + var termio unix.Termio + err := unix.IoctlSetTermio(int(fd), unix.TCGETA, &termio) + return err == nil +} diff --git a/vendor/github.com/mattn/go-isatty/isatty_windows.go b/vendor/github.com/mattn/go-isatty/isatty_windows.go new file mode 100644 index 0000000..83c398b --- /dev/null +++ b/vendor/github.com/mattn/go-isatty/isatty_windows.go @@ -0,0 +1,19 @@ +// +build windows +// +build !appengine + +package isatty + +import ( + "syscall" + "unsafe" +) + +var kernel32 = syscall.NewLazyDLL("kernel32.dll") +var procGetConsoleMode = kernel32.NewProc("GetConsoleMode") + +// IsTerminal return true if the file descriptor is terminal. +func IsTerminal(fd uintptr) bool { + var st uint32 + r, _, e := syscall.Syscall(procGetConsoleMode.Addr(), 2, fd, uintptr(unsafe.Pointer(&st)), 0) + return r != 0 && e == 0 +} diff --git a/vendor/github.com/mattn/go-runewidth/LICENSE b/vendor/github.com/mattn/go-runewidth/LICENSE new file mode 100644 index 0000000..91b5cef --- /dev/null +++ b/vendor/github.com/mattn/go-runewidth/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2016 Yasuhiro Matsumoto + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/vendor/github.com/mattn/go-runewidth/README.mkd b/vendor/github.com/mattn/go-runewidth/README.mkd new file mode 100644 index 0000000..66663a9 --- /dev/null +++ b/vendor/github.com/mattn/go-runewidth/README.mkd @@ -0,0 +1,27 @@ +go-runewidth +============ + +[![Build Status](https://travis-ci.org/mattn/go-runewidth.png?branch=master)](https://travis-ci.org/mattn/go-runewidth) +[![Coverage Status](https://coveralls.io/repos/mattn/go-runewidth/badge.png?branch=HEAD)](https://coveralls.io/r/mattn/go-runewidth?branch=HEAD) +[![GoDoc](https://godoc.org/github.com/mattn/go-runewidth?status.svg)](http://godoc.org/github.com/mattn/go-runewidth) +[![Go Report Card](https://goreportcard.com/badge/github.com/mattn/go-runewidth)](https://goreportcard.com/report/github.com/mattn/go-runewidth) + +Provides functions to get fixed width of the character or string. + +Usage +----- + +```go +runewidth.StringWidth("つのだ☆HIRO") == 12 +``` + + +Author +------ + +Yasuhiro Matsumoto + +License +------- + +under the MIT License: http://mattn.mit-license.org/2013 diff --git a/vendor/github.com/mattn/go-runewidth/runewidth.go b/vendor/github.com/mattn/go-runewidth/runewidth.go new file mode 100644 index 0000000..3e73065 --- /dev/null +++ b/vendor/github.com/mattn/go-runewidth/runewidth.go @@ -0,0 +1,481 @@ +package runewidth + +var ( + // EastAsianWidth will be set true if the current locale is CJK + EastAsianWidth = IsEastAsian() + + // DefaultCondition is a condition in current locale + DefaultCondition = &Condition{EastAsianWidth} +) + +type interval struct { + first rune + last rune +} + +var combining = []interval{ + {0x0300, 0x036F}, {0x0483, 0x0486}, {0x0488, 0x0489}, + {0x0591, 0x05BD}, {0x05BF, 0x05BF}, {0x05C1, 0x05C2}, + {0x05C4, 0x05C5}, {0x05C7, 0x05C7}, {0x0600, 0x0603}, + {0x0610, 0x0615}, {0x064B, 0x065E}, {0x0670, 0x0670}, + {0x06D6, 0x06E4}, {0x06E7, 0x06E8}, {0x06EA, 0x06ED}, + {0x070F, 0x070F}, {0x0711, 0x0711}, {0x0730, 0x074A}, + {0x07A6, 0x07B0}, {0x07EB, 0x07F3}, {0x0901, 0x0902}, + {0x093C, 0x093C}, {0x0941, 0x0948}, {0x094D, 0x094D}, + {0x0951, 0x0954}, {0x0962, 0x0963}, {0x0981, 0x0981}, + {0x09BC, 0x09BC}, {0x09C1, 0x09C4}, {0x09CD, 0x09CD}, + {0x09E2, 0x09E3}, {0x0A01, 0x0A02}, {0x0A3C, 0x0A3C}, + {0x0A41, 0x0A42}, {0x0A47, 0x0A48}, {0x0A4B, 0x0A4D}, + {0x0A70, 0x0A71}, {0x0A81, 0x0A82}, {0x0ABC, 0x0ABC}, + {0x0AC1, 0x0AC5}, {0x0AC7, 0x0AC8}, {0x0ACD, 0x0ACD}, + {0x0AE2, 0x0AE3}, {0x0B01, 0x0B01}, {0x0B3C, 0x0B3C}, + {0x0B3F, 0x0B3F}, {0x0B41, 0x0B43}, {0x0B4D, 0x0B4D}, + {0x0B56, 0x0B56}, {0x0B82, 0x0B82}, {0x0BC0, 0x0BC0}, + {0x0BCD, 0x0BCD}, {0x0C3E, 0x0C40}, {0x0C46, 0x0C48}, + {0x0C4A, 0x0C4D}, {0x0C55, 0x0C56}, {0x0CBC, 0x0CBC}, + {0x0CBF, 0x0CBF}, {0x0CC6, 0x0CC6}, {0x0CCC, 0x0CCD}, + {0x0CE2, 0x0CE3}, {0x0D41, 0x0D43}, {0x0D4D, 0x0D4D}, + {0x0DCA, 0x0DCA}, {0x0DD2, 0x0DD4}, {0x0DD6, 0x0DD6}, + {0x0E31, 0x0E31}, {0x0E34, 0x0E3A}, {0x0E47, 0x0E4E}, + {0x0EB1, 0x0EB1}, {0x0EB4, 0x0EB9}, {0x0EBB, 0x0EBC}, + {0x0EC8, 0x0ECD}, {0x0F18, 0x0F19}, {0x0F35, 0x0F35}, + {0x0F37, 0x0F37}, {0x0F39, 0x0F39}, {0x0F71, 0x0F7E}, + {0x0F80, 0x0F84}, {0x0F86, 0x0F87}, {0x0F90, 0x0F97}, + {0x0F99, 0x0FBC}, {0x0FC6, 0x0FC6}, {0x102D, 0x1030}, + {0x1032, 0x1032}, {0x1036, 0x1037}, {0x1039, 0x1039}, + {0x1058, 0x1059}, {0x1160, 0x11FF}, {0x135F, 0x135F}, + {0x1712, 0x1714}, {0x1732, 0x1734}, {0x1752, 0x1753}, + {0x1772, 0x1773}, {0x17B4, 0x17B5}, {0x17B7, 0x17BD}, + {0x17C6, 0x17C6}, {0x17C9, 0x17D3}, {0x17DD, 0x17DD}, + {0x180B, 0x180D}, {0x18A9, 0x18A9}, {0x1920, 0x1922}, + {0x1927, 0x1928}, {0x1932, 0x1932}, {0x1939, 0x193B}, + {0x1A17, 0x1A18}, {0x1B00, 0x1B03}, {0x1B34, 0x1B34}, + {0x1B36, 0x1B3A}, {0x1B3C, 0x1B3C}, {0x1B42, 0x1B42}, + {0x1B6B, 0x1B73}, {0x1DC0, 0x1DCA}, {0x1DFE, 0x1DFF}, + {0x200B, 0x200F}, {0x202A, 0x202E}, {0x2060, 0x2063}, + {0x206A, 0x206F}, {0x20D0, 0x20EF}, {0x302A, 0x302F}, + {0x3099, 0x309A}, {0xA806, 0xA806}, {0xA80B, 0xA80B}, + {0xA825, 0xA826}, {0xFB1E, 0xFB1E}, {0xFE00, 0xFE0F}, + {0xFE20, 0xFE23}, {0xFEFF, 0xFEFF}, {0xFFF9, 0xFFFB}, + {0x10A01, 0x10A03}, {0x10A05, 0x10A06}, {0x10A0C, 0x10A0F}, + {0x10A38, 0x10A3A}, {0x10A3F, 0x10A3F}, {0x1D167, 0x1D169}, + {0x1D173, 0x1D182}, {0x1D185, 0x1D18B}, {0x1D1AA, 0x1D1AD}, + {0x1D242, 0x1D244}, {0xE0001, 0xE0001}, {0xE0020, 0xE007F}, + {0xE0100, 0xE01EF}, +} + +type ctype int + +const ( + narrow ctype = iota + ambiguous + wide + halfwidth + fullwidth + neutral +) + +type intervalType struct { + first rune + last rune + ctype ctype +} + +var ctypes = []intervalType{ + {0x0020, 0x007E, narrow}, + {0x00A1, 0x00A1, ambiguous}, + {0x00A2, 0x00A3, narrow}, + {0x00A4, 0x00A4, ambiguous}, + {0x00A5, 0x00A6, narrow}, + {0x00A7, 0x00A8, ambiguous}, + {0x00AA, 0x00AA, ambiguous}, + {0x00AC, 0x00AC, narrow}, + {0x00AD, 0x00AE, ambiguous}, + {0x00AF, 0x00AF, narrow}, + {0x00B0, 0x00B4, ambiguous}, + {0x00B6, 0x00BA, ambiguous}, + {0x00BC, 0x00BF, ambiguous}, + {0x00C6, 0x00C6, ambiguous}, + {0x00D0, 0x00D0, ambiguous}, + {0x00D7, 0x00D8, ambiguous}, + {0x00DE, 0x00E1, ambiguous}, + {0x00E6, 0x00E6, ambiguous}, + {0x00E8, 0x00EA, ambiguous}, + {0x00EC, 0x00ED, ambiguous}, + {0x00F0, 0x00F0, ambiguous}, + {0x00F2, 0x00F3, ambiguous}, + {0x00F7, 0x00FA, ambiguous}, + {0x00FC, 0x00FC, ambiguous}, + {0x00FE, 0x00FE, ambiguous}, + {0x0101, 0x0101, ambiguous}, + {0x0111, 0x0111, ambiguous}, + {0x0113, 0x0113, ambiguous}, + {0x011B, 0x011B, ambiguous}, + {0x0126, 0x0127, ambiguous}, + {0x012B, 0x012B, ambiguous}, + {0x0131, 0x0133, ambiguous}, + {0x0138, 0x0138, ambiguous}, + {0x013F, 0x0142, ambiguous}, + {0x0144, 0x0144, ambiguous}, + {0x0148, 0x014B, ambiguous}, + {0x014D, 0x014D, ambiguous}, + {0x0152, 0x0153, ambiguous}, + {0x0166, 0x0167, ambiguous}, + {0x016B, 0x016B, ambiguous}, + {0x01CE, 0x01CE, ambiguous}, + {0x01D0, 0x01D0, ambiguous}, + {0x01D2, 0x01D2, ambiguous}, + {0x01D4, 0x01D4, ambiguous}, + {0x01D6, 0x01D6, ambiguous}, + {0x01D8, 0x01D8, ambiguous}, + {0x01DA, 0x01DA, ambiguous}, + {0x01DC, 0x01DC, ambiguous}, + {0x0251, 0x0251, ambiguous}, + {0x0261, 0x0261, ambiguous}, + {0x02C4, 0x02C4, ambiguous}, + {0x02C7, 0x02C7, ambiguous}, + {0x02C9, 0x02CB, ambiguous}, + {0x02CD, 0x02CD, ambiguous}, + {0x02D0, 0x02D0, ambiguous}, + {0x02D8, 0x02DB, ambiguous}, + {0x02DD, 0x02DD, ambiguous}, + {0x02DF, 0x02DF, ambiguous}, + {0x0300, 0x036F, ambiguous}, + {0x0391, 0x03A2, ambiguous}, + {0x03A3, 0x03A9, ambiguous}, + {0x03B1, 0x03C1, ambiguous}, + {0x03C3, 0x03C9, ambiguous}, + {0x0401, 0x0401, ambiguous}, + {0x0410, 0x044F, ambiguous}, + {0x0451, 0x0451, ambiguous}, + {0x1100, 0x115F, wide}, + {0x2010, 0x2010, ambiguous}, + {0x2013, 0x2016, ambiguous}, + {0x2018, 0x2019, ambiguous}, + {0x201C, 0x201D, ambiguous}, + {0x2020, 0x2022, ambiguous}, + {0x2024, 0x2027, ambiguous}, + {0x2030, 0x2030, ambiguous}, + {0x2032, 0x2033, ambiguous}, + {0x2035, 0x2035, ambiguous}, + {0x203B, 0x203B, ambiguous}, + {0x203E, 0x203E, ambiguous}, + {0x2074, 0x2074, ambiguous}, + {0x207F, 0x207F, ambiguous}, + {0x2081, 0x2084, ambiguous}, + {0x20A9, 0x20A9, halfwidth}, + {0x20AC, 0x20AC, ambiguous}, + {0x2103, 0x2103, ambiguous}, + {0x2105, 0x2105, ambiguous}, + {0x2109, 0x2109, ambiguous}, + {0x2113, 0x2113, ambiguous}, + {0x2116, 0x2116, ambiguous}, + {0x2121, 0x2122, ambiguous}, + {0x2126, 0x2126, ambiguous}, + {0x212B, 0x212B, ambiguous}, + {0x2153, 0x2154, ambiguous}, + {0x215B, 0x215E, ambiguous}, + {0x2160, 0x216B, ambiguous}, + {0x2170, 0x2179, ambiguous}, + {0x2189, 0x218A, ambiguous}, + {0x2190, 0x2199, ambiguous}, + {0x21B8, 0x21B9, ambiguous}, + {0x21D2, 0x21D2, ambiguous}, + {0x21D4, 0x21D4, ambiguous}, + {0x21E7, 0x21E7, ambiguous}, + {0x2200, 0x2200, ambiguous}, + {0x2202, 0x2203, ambiguous}, + {0x2207, 0x2208, ambiguous}, + {0x220B, 0x220B, ambiguous}, + {0x220F, 0x220F, ambiguous}, + {0x2211, 0x2211, ambiguous}, + {0x2215, 0x2215, ambiguous}, + {0x221A, 0x221A, ambiguous}, + {0x221D, 0x2220, ambiguous}, + {0x2223, 0x2223, ambiguous}, + {0x2225, 0x2225, ambiguous}, + {0x2227, 0x222C, ambiguous}, + {0x222E, 0x222E, ambiguous}, + {0x2234, 0x2237, ambiguous}, + {0x223C, 0x223D, ambiguous}, + {0x2248, 0x2248, ambiguous}, + {0x224C, 0x224C, ambiguous}, + {0x2252, 0x2252, ambiguous}, + {0x2260, 0x2261, ambiguous}, + {0x2264, 0x2267, ambiguous}, + {0x226A, 0x226B, ambiguous}, + {0x226E, 0x226F, ambiguous}, + {0x2282, 0x2283, ambiguous}, + {0x2286, 0x2287, ambiguous}, + {0x2295, 0x2295, ambiguous}, + {0x2299, 0x2299, ambiguous}, + {0x22A5, 0x22A5, ambiguous}, + {0x22BF, 0x22BF, ambiguous}, + {0x2312, 0x2312, ambiguous}, + {0x2329, 0x232A, wide}, + {0x2460, 0x24E9, ambiguous}, + {0x24EB, 0x254B, ambiguous}, + {0x2550, 0x2573, ambiguous}, + {0x2580, 0x258F, ambiguous}, + {0x2592, 0x2595, ambiguous}, + {0x25A0, 0x25A1, ambiguous}, + {0x25A3, 0x25A9, ambiguous}, + {0x25B2, 0x25B3, ambiguous}, + {0x25B6, 0x25B7, ambiguous}, + {0x25BC, 0x25BD, ambiguous}, + {0x25C0, 0x25C1, ambiguous}, + {0x25C6, 0x25C8, ambiguous}, + {0x25CB, 0x25CB, ambiguous}, + {0x25CE, 0x25D1, ambiguous}, + {0x25E2, 0x25E5, ambiguous}, + {0x25EF, 0x25EF, ambiguous}, + {0x2605, 0x2606, ambiguous}, + {0x2609, 0x2609, ambiguous}, + {0x260E, 0x260F, ambiguous}, + {0x2614, 0x2615, ambiguous}, + {0x261C, 0x261C, ambiguous}, + {0x261E, 0x261E, ambiguous}, + {0x2640, 0x2640, ambiguous}, + {0x2642, 0x2642, ambiguous}, + {0x2660, 0x2661, ambiguous}, + {0x2663, 0x2665, ambiguous}, + {0x2667, 0x266A, ambiguous}, + {0x266C, 0x266D, ambiguous}, + {0x266F, 0x266F, ambiguous}, + {0x269E, 0x269F, ambiguous}, + {0x26BE, 0x26BF, ambiguous}, + {0x26C4, 0x26CD, ambiguous}, + {0x26CF, 0x26E1, ambiguous}, + {0x26E3, 0x26E3, ambiguous}, + {0x26E8, 0x26FF, ambiguous}, + {0x273D, 0x273D, ambiguous}, + {0x2757, 0x2757, ambiguous}, + {0x2776, 0x277F, ambiguous}, + {0x27E6, 0x27ED, narrow}, + {0x2985, 0x2986, narrow}, + {0x2B55, 0x2B59, ambiguous}, + {0x2E80, 0x2E9A, wide}, + {0x2E9B, 0x2EF4, wide}, + {0x2F00, 0x2FD6, wide}, + {0x2FF0, 0x2FFC, wide}, + {0x3000, 0x3000, fullwidth}, + {0x3001, 0x303E, wide}, + {0x3041, 0x3097, wide}, + {0x3099, 0x3100, wide}, + {0x3105, 0x312E, wide}, + {0x3131, 0x318F, wide}, + {0x3190, 0x31BB, wide}, + {0x31C0, 0x31E4, wide}, + {0x31F0, 0x321F, wide}, + {0x3220, 0x3247, wide}, + {0x3248, 0x324F, ambiguous}, + {0x3250, 0x32FF, wide}, + {0x3300, 0x4DBF, wide}, + {0x4E00, 0xA48D, wide}, + {0xA490, 0xA4C7, wide}, + {0xA960, 0xA97D, wide}, + {0xAC00, 0xD7A4, wide}, + {0xE000, 0xF8FF, ambiguous}, + {0xF900, 0xFAFF, wide}, + {0xFE00, 0xFE0F, ambiguous}, + {0xFE10, 0xFE1A, wide}, + {0xFE30, 0xFE53, wide}, + {0xFE54, 0xFE67, wide}, + {0xFE68, 0xFE6C, wide}, + {0xFF01, 0xFF60, fullwidth}, + {0xFF61, 0xFFBF, halfwidth}, + {0xFFC2, 0xFFC8, halfwidth}, + {0xFFCA, 0xFFD0, halfwidth}, + {0xFFD2, 0xFFD8, halfwidth}, + {0xFFDA, 0xFFDD, halfwidth}, + {0xFFE0, 0xFFE7, fullwidth}, + {0xFFE8, 0xFFEF, halfwidth}, + {0xFFFD, 0xFFFE, ambiguous}, + {0x1B000, 0x1B002, wide}, + {0x1F100, 0x1F10A, ambiguous}, + {0x1F110, 0x1F12D, ambiguous}, + {0x1F130, 0x1F169, ambiguous}, + {0x1F170, 0x1F19B, ambiguous}, + {0x1F200, 0x1F203, wide}, + {0x1F210, 0x1F23B, wide}, + {0x1F240, 0x1F249, wide}, + {0x1F250, 0x1F252, wide}, + {0x20000, 0x2FFFE, wide}, + {0x30000, 0x3FFFE, wide}, + {0xE0100, 0xE01F0, ambiguous}, + {0xF0000, 0xFFFFD, ambiguous}, + {0x100000, 0x10FFFE, ambiguous}, +} + +// Condition have flag EastAsianWidth whether the current locale is CJK or not. +type Condition struct { + EastAsianWidth bool +} + +// NewCondition return new instance of Condition which is current locale. +func NewCondition() *Condition { + return &Condition{EastAsianWidth} +} + +// RuneWidth returns the number of cells in r. +// See http://www.unicode.org/reports/tr11/ +func (c *Condition) RuneWidth(r rune) int { + if r == 0 { + return 0 + } + if r < 32 || (r >= 0x7f && r < 0xa0) { + return 1 + } + for _, iv := range combining { + if iv.first <= r && r <= iv.last { + return 0 + } + } + + if c.EastAsianWidth && IsAmbiguousWidth(r) { + return 2 + } + + if r >= 0x1100 && + (r <= 0x115f || r == 0x2329 || r == 0x232a || + (r >= 0x2e80 && r <= 0xa4cf && r != 0x303f) || + (r >= 0xac00 && r <= 0xd7a3) || + (r >= 0xf900 && r <= 0xfaff) || + (r >= 0xfe30 && r <= 0xfe6f) || + (r >= 0xff00 && r <= 0xff60) || + (r >= 0xffe0 && r <= 0xffe6) || + (r >= 0x20000 && r <= 0x2fffd) || + (r >= 0x30000 && r <= 0x3fffd)) { + return 2 + } + return 1 +} + +// StringWidth return width as you can see +func (c *Condition) StringWidth(s string) (width int) { + for _, r := range []rune(s) { + width += c.RuneWidth(r) + } + return width +} + +// Truncate return string truncated with w cells +func (c *Condition) Truncate(s string, w int, tail string) string { + if c.StringWidth(s) <= w { + return s + } + r := []rune(s) + tw := c.StringWidth(tail) + w -= tw + width := 0 + i := 0 + for ; i < len(r); i++ { + cw := c.RuneWidth(r[i]) + if width+cw > w { + break + } + width += cw + } + return string(r[0:i]) + tail +} + +// Wrap return string wrapped with w cells +func (c *Condition) Wrap(s string, w int) string { + width := 0 + out := "" + for _, r := range []rune(s) { + cw := RuneWidth(r) + if r == '\n' { + out += string(r) + width = 0 + continue + } else if width+cw > w { + out += "\n" + width = 0 + out += string(r) + width += cw + continue + } + out += string(r) + width += cw + } + return out +} + +// FillLeft return string filled in left by spaces in w cells +func (c *Condition) FillLeft(s string, w int) string { + width := c.StringWidth(s) + count := w - width + if count > 0 { + b := make([]byte, count) + for i := range b { + b[i] = ' ' + } + return string(b) + s + } + return s +} + +// FillRight return string filled in left by spaces in w cells +func (c *Condition) FillRight(s string, w int) string { + width := c.StringWidth(s) + count := w - width + if count > 0 { + b := make([]byte, count) + for i := range b { + b[i] = ' ' + } + return s + string(b) + } + return s +} + +// RuneWidth returns the number of cells in r. +// See http://www.unicode.org/reports/tr11/ +func RuneWidth(r rune) int { + return DefaultCondition.RuneWidth(r) +} + +func ct(r rune) ctype { + for _, iv := range ctypes { + if iv.first <= r && r <= iv.last { + return iv.ctype + } + } + return neutral +} + +// IsAmbiguousWidth returns whether is ambiguous width or not. +func IsAmbiguousWidth(r rune) bool { + return ct(r) == ambiguous +} + +// IsNeutralWidth returns whether is neutral width or not. +func IsNeutralWidth(r rune) bool { + return ct(r) == neutral +} + +// StringWidth return width as you can see +func StringWidth(s string) (width int) { + return DefaultCondition.StringWidth(s) +} + +// Truncate return string truncated with w cells +func Truncate(s string, w int, tail string) string { + return DefaultCondition.Truncate(s, w, tail) +} + +// Wrap return string wrapped with w cells +func Wrap(s string, w int) string { + return DefaultCondition.Wrap(s, w) +} + +// FillLeft return string filled in left by spaces in w cells +func FillLeft(s string, w int) string { + return DefaultCondition.FillLeft(s, w) +} + +// FillRight return string filled in left by spaces in w cells +func FillRight(s string, w int) string { + return DefaultCondition.FillRight(s, w) +} diff --git a/vendor/github.com/mattn/go-runewidth/runewidth_js.go b/vendor/github.com/mattn/go-runewidth/runewidth_js.go new file mode 100644 index 0000000..0ce32c5 --- /dev/null +++ b/vendor/github.com/mattn/go-runewidth/runewidth_js.go @@ -0,0 +1,8 @@ +// +build js + +package runewidth + +func IsEastAsian() bool { + // TODO: Implement this for the web. Detect east asian in a compatible way, and return true. + return false +} diff --git a/vendor/github.com/mattn/go-runewidth/runewidth_posix.go b/vendor/github.com/mattn/go-runewidth/runewidth_posix.go new file mode 100644 index 0000000..c579e9a --- /dev/null +++ b/vendor/github.com/mattn/go-runewidth/runewidth_posix.go @@ -0,0 +1,77 @@ +// +build !windows,!js + +package runewidth + +import ( + "os" + "regexp" + "strings" +) + +var reLoc = regexp.MustCompile(`^[a-z][a-z][a-z]?(?:_[A-Z][A-Z])?\.(.+)`) + +var mblenTable = map[string]int{ + "utf-8": 6, + "utf8": 6, + "jis": 8, + "eucjp": 3, + "euckr": 2, + "euccn": 2, + "sjis": 2, + "cp932": 2, + "cp51932": 2, + "cp936": 2, + "cp949": 2, + "cp950": 2, + "big5": 2, + "gbk": 2, + "gb2312": 2, +} + +func isEastAsian(locale string) bool { + charset := strings.ToLower(locale) + r := reLoc.FindStringSubmatch(locale) + if len(r) == 2 { + charset = strings.ToLower(r[1]) + } + + if strings.HasSuffix(charset, "@cjk_narrow") { + return false + } + + for pos, b := range []byte(charset) { + if b == '@' { + charset = charset[:pos] + break + } + } + max := 1 + if m, ok := mblenTable[charset]; ok { + max = m + } + if max > 1 && (charset[0] != 'u' || + strings.HasPrefix(locale, "ja") || + strings.HasPrefix(locale, "ko") || + strings.HasPrefix(locale, "zh")) { + return true + } + return false +} + +// IsEastAsian return true if the current locale is CJK +func IsEastAsian() bool { + locale := os.Getenv("LC_CTYPE") + if locale == "" { + locale = os.Getenv("LANG") + } + + // ignore C locale + if locale == "POSIX" || locale == "C" { + return false + } + if len(locale) > 1 && locale[0] == 'C' && (locale[1] == '.' || locale[1] == '-') { + return false + } + + return isEastAsian(locale) +} diff --git a/vendor/github.com/mattn/go-runewidth/runewidth_windows.go b/vendor/github.com/mattn/go-runewidth/runewidth_windows.go new file mode 100644 index 0000000..0258876 --- /dev/null +++ b/vendor/github.com/mattn/go-runewidth/runewidth_windows.go @@ -0,0 +1,25 @@ +package runewidth + +import ( + "syscall" +) + +var ( + kernel32 = syscall.NewLazyDLL("kernel32") + procGetConsoleOutputCP = kernel32.NewProc("GetConsoleOutputCP") +) + +// IsEastAsian return true if the current locale is CJK +func IsEastAsian() bool { + r1, _, _ := procGetConsoleOutputCP.Call() + if r1 == 0 { + return false + } + + switch int(r1) { + case 932, 51932, 936, 949, 950: + return true + } + + return false +} diff --git a/vendor/github.com/mitchellh/mapstructure/mapstructure.go b/vendor/github.com/mitchellh/mapstructure/mapstructure.go index d1cb607..bd46603 100644 --- a/vendor/github.com/mitchellh/mapstructure/mapstructure.go +++ b/vendor/github.com/mitchellh/mapstructure/mapstructure.go @@ -1,5 +1,5 @@ // The mapstructure package exposes functionality to convert an -// abitrary map[string]interface{} into a native Go structure. +// arbitrary map[string]interface{} into a native Go structure. // // The Go structure can be arbitrarily complex, containing slices, // other structs, etc. and the decoder will properly decode nested @@ -202,7 +202,7 @@ func (d *Decoder) decode(name string, data interface{}, val reflect.Value) error d.config.DecodeHook, dataVal.Type(), val.Type(), data) if err != nil { - return err + return fmt.Errorf("error decoding '%s': %s", name, err) } } @@ -229,6 +229,8 @@ func (d *Decoder) decode(name string, data interface{}, val reflect.Value) error err = d.decodePtr(name, data, val) case reflect.Slice: err = d.decodeSlice(name, data, val) + case reflect.Func: + err = d.decodeFunc(name, data, val) default: // If we reached this point then we weren't able to decode it return fmt.Errorf("%s: unsupported type: %s", name, dataKind) @@ -546,7 +548,12 @@ func (d *Decoder) decodePtr(name string, data interface{}, val reflect.Value) er // into that. Then set the value of the pointer to this type. valType := val.Type() valElemType := valType.Elem() - realVal := reflect.New(valElemType) + + realVal := val + if realVal.IsNil() || d.config.ZeroFields { + realVal = reflect.New(valElemType) + } + if err := d.decode(name, data, reflect.Indirect(realVal)); err != nil { return err } @@ -555,6 +562,19 @@ func (d *Decoder) decodePtr(name string, data interface{}, val reflect.Value) er return nil } +func (d *Decoder) decodeFunc(name string, data interface{}, val reflect.Value) error { + // Create an element of the concrete (non pointer) type and decode + // into that. Then set the value of the pointer to this type. + dataVal := reflect.Indirect(reflect.ValueOf(data)) + if val.Type() != dataVal.Type() { + return fmt.Errorf( + "'%s' expected type '%s', got unconvertible type '%s'", + name, val.Type(), dataVal.Type()) + } + val.Set(dataVal) + return nil +} + func (d *Decoder) decodeSlice(name string, data interface{}, val reflect.Value) error { dataVal := reflect.Indirect(reflect.ValueOf(data)) dataValKind := dataVal.Kind() @@ -562,20 +582,24 @@ func (d *Decoder) decodeSlice(name string, data interface{}, val reflect.Value) valElemType := valType.Elem() sliceType := reflect.SliceOf(valElemType) - // Check input type - if dataValKind != reflect.Array && dataValKind != reflect.Slice { - // Accept empty map instead of array/slice in weakly typed mode - if d.config.WeaklyTypedInput && dataVal.Kind() == reflect.Map && dataVal.Len() == 0 { - val.Set(reflect.MakeSlice(sliceType, 0, 0)) - return nil - } else { - return fmt.Errorf( - "'%s': source data must be an array or slice, got %s", name, dataValKind) + valSlice := val + if valSlice.IsNil() || d.config.ZeroFields { + + // Check input type + if dataValKind != reflect.Array && dataValKind != reflect.Slice { + // Accept empty map instead of array/slice in weakly typed mode + if d.config.WeaklyTypedInput && dataVal.Kind() == reflect.Map && dataVal.Len() == 0 { + val.Set(reflect.MakeSlice(sliceType, 0, 0)) + return nil + } else { + return fmt.Errorf( + "'%s': source data must be an array or slice, got %s", name, dataValKind) + } } - } - // Make a new slice to hold our result, same size as the original data. - valSlice := reflect.MakeSlice(sliceType, dataVal.Len(), dataVal.Len()) + // Make a new slice to hold our result, same size as the original data. + valSlice = reflect.MakeSlice(sliceType, dataVal.Len(), dataVal.Len()) + } // Accumulate any errors errors := make([]string, 0) @@ -651,14 +675,6 @@ func (d *Decoder) decodeStruct(name string, data interface{}, val reflect.Value) fieldType := structType.Field(i) fieldKind := fieldType.Type.Kind() - if fieldType.Anonymous { - if fieldKind != reflect.Struct { - errors = appendErrors(errors, - fmt.Errorf("%s: unsupported type: %s", fieldType.Name, fieldKind)) - continue - } - } - // If "squash" is specified in the tag, we squash the field down. squash := false tagParts := strings.Split(fieldType.Tag.Get(d.config.TagName), ",") diff --git a/vendor/github.com/mvdan/xurls/LICENSE b/vendor/github.com/mvdan/xurls/LICENSE deleted file mode 100644 index 7d71d51..0000000 --- a/vendor/github.com/mvdan/xurls/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -Copyright (c) 2015, Daniel Martí. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of the copyright holder nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/mvdan/xurls/README.md b/vendor/github.com/mvdan/xurls/README.md deleted file mode 100644 index 2051d14..0000000 --- a/vendor/github.com/mvdan/xurls/README.md +++ /dev/null @@ -1,40 +0,0 @@ -# xurls - -[![GoDoc](https://godoc.org/github.com/mvdan/xurls?status.svg)](https://godoc.org/github.com/mvdan/xurls) -[![Travis](https://travis-ci.org/mvdan/xurls.svg?branch=master)](https://travis-ci.org/mvdan/xurls) - -Extract urls from text using regular expressions. - - go get -u github.com/mvdan/xurls - -```go -import "github.com/mvdan/xurls" - -func main() { - xurls.Relaxed.FindString("Do gophers live in golang.org?") - // "golang.org" - xurls.Strict.FindAllString("foo.com is http://foo.com/.", -1) - // []string{"http://foo.com/"} -} -``` - -`Relaxed` is around five times slower than `Strict` since it does more -work to find the URLs without relying on the scheme: - -``` -BenchmarkStrictEmpty-4 1000000 1885 ns/op -BenchmarkStrictSingle-4 200000 8356 ns/op -BenchmarkStrictMany-4 100000 22547 ns/op -BenchmarkRelaxedEmpty-4 200000 7284 ns/op -BenchmarkRelaxedSingle-4 30000 58557 ns/op -BenchmarkRelaxedMany-4 10000 130251 ns/op -``` - -#### cmd/xurls - - go get -u github.com/mvdan/xurls/cmd/xurls - -```shell -$ echo "Do gophers live in http://golang.org?" | xurls -http://golang.org -``` diff --git a/vendor/github.com/mvdan/xurls/regex.go b/vendor/github.com/mvdan/xurls/regex.go deleted file mode 100644 index b611069..0000000 --- a/vendor/github.com/mvdan/xurls/regex.go +++ /dev/null @@ -1,8 +0,0 @@ -// Generated by regexgen - -package xurls - -const ( - gtld = `(?i)(aaa|aarp|abarth|abb|abbott|abbvie|abc|able|abogado|abudhabi|ac|academy|accenture|accountant|accountants|aco|active|actor|ad|adac|ads|adult|ae|aeg|aero|aetna|af|afamilycompany|afl|africa|ag|agakhan|agency|ai|aig|aigo|airbus|airforce|airtel|akdn|al|alfaromeo|alibaba|alipay|allfinanz|allstate|ally|alsace|alstom|am|americanexpress|americanfamily|amex|amfam|amica|amsterdam|analytics|android|anquan|anz|ao|aol|apartments|app|apple|aq|aquarelle|ar|arab|aramco|archi|army|arpa|art|arte|as|asda|asia|associates|at|athleta|attorney|au|auction|audi|audible|audio|auspost|author|auto|autos|avianca|aw|aws|ax|axa|az|azure|ba|baby|baidu|banamex|bananarepublic|band|bank|bar|barcelona|barclaycard|barclays|barefoot|bargains|baseball|basketball|bauhaus|bayern|bb|bbc|bbt|bbva|bcg|bcn|bd|be|beats|beauty|beer|bentley|berlin|best|bestbuy|bet|bf|bg|bh|bharti|bi|bible|bid|bike|bing|bingo|bio|bit|biz|bj|black|blackfriday|blanco|blockbuster|blog|bloomberg|blue|bm|bms|bmw|bn|bnl|bnpparibas|bo|boats|boehringer|bofa|bom|bond|boo|book|booking|boots|bosch|bostik|boston|bot|boutique|box|br|bradesco|bridgestone|broadway|broker|brother|brussels|bs|bt|budapest|bugatti|build|builders|business|buy|buzz|bv|bw|by|bz|bzh|ca|cab|cafe|cal|call|calvinklein|cam|camera|camp|cancerresearch|canon|capetown|capital|capitalone|car|caravan|cards|care|career|careers|cars|cartier|casa|case|caseih|cash|casino|cat|catering|catholic|cba|cbn|cbre|cbs|cc|cd|ceb|center|ceo|cern|cf|cfa|cfd|cg|ch|chanel|channel|chase|chat|cheap|chintai|chloe|christmas|chrome|chrysler|church|ci|cipriani|circle|cisco|citadel|citi|citic|city|cityeats|ck|cl|claims|cleaning|click|clinic|clinique|clothing|cloud|club|clubmed|cm|cn|co|coach|codes|coffee|college|cologne|com|comcast|commbank|community|company|compare|computer|comsec|condos|construction|consulting|contact|contractors|cooking|cookingchannel|cool|coop|corsica|country|coupon|coupons|courses|cr|credit|creditcard|creditunion|cricket|crown|crs|cruise|cruises|csc|cu|cuisinella|cv|cw|cx|cy|cymru|cyou|cz|dabur|dad|dance|data|date|dating|datsun|day|dclk|dds|de|deal|dealer|deals|degree|delivery|dell|deloitte|delta|democrat|dental|dentist|desi|design|dev|dhl|diamonds|diet|digital|direct|directory|discount|discover|dish|diy|dj|dk|dm|dnp|do|docs|doctor|dodge|dog|doha|domains|dot|download|drive|dtv|dubai|duck|dunlop|duns|dupont|durban|dvag|dvr|dwg|dz|earth|eat|ec|eco|edeka|edu|education|ee|eg|email|emerck|emerson|energy|engineer|engineering|enterprises|epost|epson|equipment|er|ericsson|erni|es|esq|estate|esurance|et|etisalat|eu|eurovision|eus|events|everbank|example|exchange|exit|expert|exposed|express|extraspace|fage|fail|fairwinds|faith|family|fan|fans|farm|farmers|fashion|fast|fedex|feedback|ferrari|ferrero|fi|fiat|fidelity|fido|film|final|finance|financial|fire|firestone|firmdale|fish|fishing|fit|fitness|fj|fk|flickr|flights|flir|florist|flowers|fly|fm|fo|foo|food|foodnetwork|football|ford|forex|forsale|forum|foundation|fox|fr|free|fresenius|frl|frogans|frontdoor|frontier|ftr|fujitsu|fujixerox|fun|fund|furniture|futbol|fyi|ga|gal|gallery|gallo|gallup|game|games|gap|garden|gb|gbiz|gd|gdn|ge|gea|gent|genting|george|gf|gg|ggee|gh|gi|gift|gifts|gives|giving|gl|glade|glass|gle|global|globo|gm|gmail|gmbh|gmo|gmx|gn|gnu|godaddy|gold|goldpoint|golf|goo|goodhands|goodyear|goog|google|gop|got|gov|gp|gq|gr|grainger|graphics|gratis|green|gripe|grocery|group|gs|gt|gu|guardian|gucci|guge|guide|guitars|guru|gw|gy|hair|hamburg|hangout|haus|hbo|hdfc|hdfcbank|health|healthcare|help|helsinki|here|hermes|hgtv|hiphop|hisamitsu|hitachi|hiv|hk|hkt|hm|hn|hockey|holdings|holiday|homedepot|homegoods|homes|homesense|honda|honeywell|horse|host|hosting|hot|hoteles|hotels|hotmail|house|how|hr|hsbc|ht|htc|hu|hughes|hyatt|hyundai|i2p|ibm|icbc|ice|icu|id|ie|ieee|ifm|iinet|ikano|il|im|imamat|imdb|immo|immobilien|in|industries|infiniti|info|ing|ink|institute|insurance|insure|int|intel|international|intuit|invalid|investments|io|ipiranga|iq|ir|irish|is|iselect|ismaili|ist|istanbul|it|itau|itv|iveco|iwc|jaguar|java|jcb|jcp|je|jeep|jetzt|jewelry|jio|jlc|jll|jm|jmp|jnj|jo|jobs|joburg|jot|joy|jp|jpmorgan|jprs|juegos|juniper|kaufen|kddi|ke|kerryhotels|kerrylogistics|kerryproperties|kfh|kg|kh|ki|kia|kim|kinder|kindle|kitchen|kiwi|km|kn|koeln|komatsu|kosher|kp|kpmg|kpn|kr|krd|kred|kuokgroup|kw|ky|kyoto|kz|la|lacaixa|ladbrokes|lamborghini|lamer|lancaster|lancia|lancome|land|landrover|lanxess|lasalle|lat|latino|latrobe|law|lawyer|lb|lc|lds|lease|leclerc|lefrak|legal|lego|lexus|lgbt|li|liaison|lidl|life|lifeinsurance|lifestyle|lighting|like|lilly|limited|limo|lincoln|linde|link|lipsy|live|living|lixil|lk|loan|loans|local|localhost|locker|locus|loft|lol|london|lotte|lotto|love|lpl|lplfinancial|lr|ls|lt|ltd|ltda|lu|lundbeck|lupin|luxe|luxury|lv|ly|ma|macys|madrid|maif|maison|makeup|man|management|mango|map|market|marketing|markets|marriott|marshalls|maserati|mattel|mba|mc|mcd|mcdonalds|mckinsey|md|me|med|media|meet|melbourne|meme|memorial|men|menu|meo|merckmsd|metlife|mg|mh|miami|microsoft|mil|mini|mint|mit|mitsubishi|mk|ml|mlb|mls|mm|mma|mn|mo|mobi|mobile|mobily|moda|moe|moi|mom|monash|money|monster|montblanc|mopar|mormon|mortgage|moscow|moto|motorcycles|mov|movie|movistar|mp|mq|mr|ms|msd|mt|mtn|mtpc|mtr|mu|museum|mutual|mutuelle|mv|mw|mx|my|mz|na|nab|nadex|nagoya|name|nationwide|natura|navy|nba|nc|ne|nec|net|netbank|netflix|network|neustar|new|newholland|news|next|nextdirect|nexus|nf|nfl|ng|ngo|nhk|ni|nico|nike|nikon|ninja|nissan|nissay|nl|no|nokia|northwesternmutual|norton|now|nowruz|nowtv|np|nr|nra|nrw|ntt|nu|nyc|nz|obi|observer|off|office|okinawa|olayan|olayangroup|oldnavy|ollo|om|omega|one|ong|onion|onl|online|onyourside|ooo|open|oracle|orange|org|organic|orientexpress|origins|osaka|otsuka|ott|ovh|pa|page|pamperedchef|panasonic|panerai|paris|pars|partners|parts|party|passagens|pay|pccw|pe|pet|pf|pfizer|pg|ph|pharmacy|phd|philips|phone|photo|photography|photos|physio|piaget|pics|pictet|pictures|pid|pin|ping|pink|pioneer|pizza|pk|pl|place|play|playstation|plumbing|plus|pm|pn|pnc|pohl|poker|politie|porn|post|pr|pramerica|praxi|press|prime|pro|prod|productions|prof|progressive|promo|properties|property|protection|pru|prudential|ps|pt|pub|pw|pwc|py|qa|qpon|quebec|quest|qvc|racing|radio|raid|re|read|realestate|realtor|realty|recipes|red|redstone|redumbrella|rehab|reise|reisen|reit|reliance|ren|rent|rentals|repair|report|republican|rest|restaurant|review|reviews|rexroth|rich|richardli|ricoh|rightathome|ril|rio|rip|rmit|ro|rocher|rocks|rodeo|rogers|room|rs|rsvp|ru|ruhr|run|rw|rwe|ryukyu|sa|saarland|safe|safety|sakura|sale|salon|samsclub|samsung|sandvik|sandvikcoromant|sanofi|sap|sapo|sarl|sas|save|saxo|sb|sbi|sbs|sc|sca|scb|schaeffler|schmidt|scholarships|school|schule|schwarz|science|scjohnson|scor|scot|sd|se|search|seat|secure|security|seek|select|sener|services|ses|seven|sew|sex|sexy|sfr|sg|sh|shangrila|sharp|shaw|shell|shia|shiksha|shoes|shop|shopping|shouji|show|showtime|shriram|si|silk|sina|singles|site|sj|sk|ski|skin|sky|skype|sl|sling|sm|smart|smile|sn|sncf|so|soccer|social|softbank|software|sohu|solar|solutions|song|sony|soy|space|spiegel|spot|spreadbetting|sr|srl|srt|st|stada|staples|star|starhub|statebank|statefarm|statoil|stc|stcgroup|stockholm|storage|store|stream|studio|study|style|su|sucks|supplies|supply|support|surf|surgery|suzuki|sv|swatch|swiftcover|swiss|sx|sy|sydney|symantec|systems|sz|tab|taipei|talk|taobao|target|tatamotors|tatar|tattoo|tax|taxi|tc|tci|td|tdk|team|tech|technology|tel|telecity|telefonica|temasek|tennis|test|teva|tf|tg|th|thd|theater|theatre|theguardian|tiaa|tickets|tienda|tiffany|tips|tires|tirol|tj|tjmaxx|tjx|tk|tkmaxx|tl|tm|tmall|tn|to|today|tokyo|tools|top|toray|toshiba|total|tours|town|toyota|toys|tr|trade|trading|training|travel|travelchannel|travelers|travelersinsurance|trust|trv|tt|tube|tui|tunes|tushu|tv|tvs|tw|tz|ua|ubank|ubs|uconnect|ug|uk|unicom|university|uno|uol|ups|us|uy|uz|va|vacations|vana|vanguard|vc|ve|vegas|ventures|verisign|vermögensberater|vermögensberatung|versicherung|vet|vg|vi|viajes|video|vig|viking|villas|vin|vip|virgin|visa|vision|vista|vistaprint|viva|vivo|vlaanderen|vn|vodka|volkswagen|volvo|vote|voting|voto|voyage|vu|vuelos|wales|walmart|walter|wang|wanggou|warman|watch|watches|weather|weatherchannel|webcam|weber|website|wed|wedding|weibo|weir|wf|whoswho|wien|wiki|williamhill|win|windows|wine|winners|wme|wolterskluwer|woodside|work|works|world|wow|ws|wtc|wtf|xbox|xerox|xfinity|xihuan|xin|xn--11b4c3d|xn--1ck2e1b|xn--1qqw23a|xn--30rr7y|xn--3bst00m|xn--3ds443g|xn--3e0b707e|xn--3oq18vl8pn36a|xn--3pxu8k|xn--42c2d9a|xn--45brj9c|xn--45q11c|xn--4gbrim|xn--4gq48lf9j|xn--54b7fta0cc|xn--55qw42g|xn--55qx5d|xn--5su34j936bgsg|xn--5tzm5g|xn--6frz82g|xn--6qq986b3xl|xn--80adxhks|xn--80ao21a|xn--80aqecdr1a|xn--80asehdb|xn--80aswg|xn--8y0a063a|xn--90a3ac|xn--90ais|xn--9dbq2a|xn--9et52u|xn--9krt00a|xn--b4w605ferd|xn--bck1b9a5dre4c|xn--c1avg|xn--c2br7g|xn--cck2b3b|xn--cg4bki|xn--clchc0ea0b2g2a9gcd|xn--czr694b|xn--czrs0t|xn--czru2d|xn--d1acj3b|xn--d1alf|xn--e1a4c|xn--eckvdtc9d|xn--efvy88h|xn--estv75g|xn--fct429k|xn--fhbei|xn--fiq228c5hs|xn--fiq64b|xn--fiqs8s|xn--fiqz9s|xn--fjq720a|xn--flw351e|xn--fpcrj9c3d|xn--fzc2c9e2c|xn--fzys8d69uvgm|xn--g2xx48c|xn--gckr3f0f|xn--gecrj9c|xn--gk3at1e|xn--h2brj9c|xn--hxt814e|xn--i1b6b1a6a2e|xn--imr513n|xn--io0a7i|xn--j1aef|xn--j1amh|xn--j6w193g|xn--jlq61u9w7b|xn--jvr189m|xn--kcrx77d1x4a|xn--kprw13d|xn--kpry57d|xn--kpu716f|xn--kput3i|xn--l1acc|xn--lgbbat1ad8j|xn--mgb2ddes|xn--mgb9awbf|xn--mgba3a3ejt|xn--mgba3a4f16a|xn--mgba3a4fra|xn--mgba7c0bbn0a|xn--mgbaakc7dvf|xn--mgbaam7a8h|xn--mgbab2bd|xn--mgbai9a5eva00b|xn--mgbai9azgqp6j|xn--mgbayh7gpa|xn--mgbb9fbpob|xn--mgbbh1a71e|xn--mgbc0a9azcg|xn--mgbca7dzdo|xn--mgberp4a5d4a87g|xn--mgberp4a5d4ar|xn--mgbi4ecexp|xn--mgbpl2fh|xn--mgbqly7c0a67fbc|xn--mgbqly7cvafr|xn--mgbt3dhd|xn--mgbtf8fl|xn--mgbtx2b|xn--mgbx4cd0ab|xn--mix082f|xn--mix891f|xn--mk1bu44c|xn--mxtq1m|xn--ngbc5azd|xn--ngbe9e0a|xn--ngbrx|xn--nnx388a|xn--node|xn--nqv7f|xn--nqv7fs00ema|xn--nyqy26a|xn--o3cw4h|xn--ogbpf8fl|xn--p1acf|xn--p1ai|xn--pbt977c|xn--pgbs0dh|xn--pssy2u|xn--q9jyb4c|xn--qcka1pmc|xn--qxam|xn--rhqv96g|xn--rovu88b|xn--s9brj9c|xn--ses554g|xn--t60b56a|xn--tckwe|xn--tiq49xqyj|xn--unup4y|xn--vermgensberater-ctb|xn--vermgensberatung-pwb|xn--vhquv|xn--vuq861b|xn--w4r85el8fhu5dnra|xn--w4rs40l|xn--wgbh1c|xn--wgbl6a|xn--xhq521b|xn--xkc2al3hye2a|xn--xkc2dl3a5ee0h|xn--y9a3aq|xn--yfro4i67o|xn--ygbi2ammx|xn--zfr164b|xperia|xxx|xyz|yachts|yahoo|yamaxun|yandex|ye|yodobashi|yoga|yokohama|you|youtube|yt|yun|za|zappos|zara|zero|zip|zippo|zkey|zm|zone|zuerich|zw|ελ|бел|дети|ею|католик|ком|мкд|мон|москва|онлайн|орг|рус|рф|сайт|срб|укр|қаз|հայ|קום|ابوظبي|اتصالات|ارامكو|الاردن|الجزائر|السعودية|السعوديه|السعودیة|السعودیۃ|العليان|المغرب|اليمن|امارات|ايران|ایران|بازار|بيتك|بھارت|تونس|سودان|سوريا|سورية|شبكة|عراق|عرب|عمان|فلسطين|قطر|كاثوليك|كوم|مصر|مليسيا|موبايلي|موقع|همراه|پاكستان|پاکستان|कॉम|नेट|भारत|संगठन|বাংলা|ভারত|ਭਾਰਤ|ભારત|இந்தியா|இலங்கை|சிங்கப்பூர்|భారత్|ලංකා|คอม|ไทย|გე|みんな|クラウド|グーグル|コム|ストア|セール|ファッション|ポイント|一号店|世界|中信|中国|中國|中文网|企业|佛山|信息|健康|八卦|公司|公益|台湾|台灣|商城|商店|商标|嘉里|嘉里大酒店|在线|大众汽车|大拿|天主教|娱乐|家電|工行|广东|微博|慈善|我爱你|手机|手表|政务|政府|新加坡|新闻|时尚|書籍|机构|淡马锡|游戏|澳門|澳门|点看|珠宝|移动|组织机构|网址|网店|网站|网络|联通|臺灣|诺基亚|谷歌|购物|通販|集团|電訊盈科|飞利浦|食品|餐厅|香格里拉|香港|닷넷|닷컴|삼성|한국)(?-i)` - otherScheme = `(?i)(bitcoin|file|magnet|mailto|sms|tel|xmpp)(?-i):` -) diff --git a/vendor/github.com/mvdan/xurls/schemes.go b/vendor/github.com/mvdan/xurls/schemes.go deleted file mode 100644 index 84767f0..0000000 --- a/vendor/github.com/mvdan/xurls/schemes.go +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright (c) 2015, Daniel Martí -// See LICENSE for licensing information - -package xurls - -// SchemesNoAuthority is a sorted list of some well-known url schemes that are -// followed by ":" instead of "://". Since these are more prone to false -// positives, we limit their matching. -var SchemesNoAuthority = []string{ - `bitcoin`, // Bitcoin - `file`, // Files - `magnet`, // Torrent magnets - `mailto`, // Mail - `sms`, // SMS - `tel`, // Telephone - `xmpp`, // XMPP -} diff --git a/vendor/github.com/mvdan/xurls/tlds.go b/vendor/github.com/mvdan/xurls/tlds.go deleted file mode 100644 index 6aef29e..0000000 --- a/vendor/github.com/mvdan/xurls/tlds.go +++ /dev/null @@ -1,1564 +0,0 @@ -// Generated by tldsgen - -package xurls - -// TLDs is a sorted list of all public top-level domains. -// -// Sources: -// * https://data.iana.org/TLD/tlds-alpha-by-domain.txt -// * https://publicsuffix.org/list/effective_tld_names.dat -var TLDs = []string{ - `aaa`, - `aarp`, - `abarth`, - `abb`, - `abbott`, - `abbvie`, - `abc`, - `able`, - `abogado`, - `abudhabi`, - `ac`, - `academy`, - `accenture`, - `accountant`, - `accountants`, - `aco`, - `active`, - `actor`, - `ad`, - `adac`, - `ads`, - `adult`, - `ae`, - `aeg`, - `aero`, - `aetna`, - `af`, - `afamilycompany`, - `afl`, - `africa`, - `ag`, - `agakhan`, - `agency`, - `ai`, - `aig`, - `aigo`, - `airbus`, - `airforce`, - `airtel`, - `akdn`, - `al`, - `alfaromeo`, - `alibaba`, - `alipay`, - `allfinanz`, - `allstate`, - `ally`, - `alsace`, - `alstom`, - `am`, - `americanexpress`, - `americanfamily`, - `amex`, - `amfam`, - `amica`, - `amsterdam`, - `analytics`, - `android`, - `anquan`, - `anz`, - `ao`, - `aol`, - `apartments`, - `app`, - `apple`, - `aq`, - `aquarelle`, - `ar`, - `arab`, - `aramco`, - `archi`, - `army`, - `arpa`, - `art`, - `arte`, - `as`, - `asda`, - `asia`, - `associates`, - `at`, - `athleta`, - `attorney`, - `au`, - `auction`, - `audi`, - `audible`, - `audio`, - `auspost`, - `author`, - `auto`, - `autos`, - `avianca`, - `aw`, - `aws`, - `ax`, - `axa`, - `az`, - `azure`, - `ba`, - `baby`, - `baidu`, - `banamex`, - `bananarepublic`, - `band`, - `bank`, - `bar`, - `barcelona`, - `barclaycard`, - `barclays`, - `barefoot`, - `bargains`, - `baseball`, - `basketball`, - `bauhaus`, - `bayern`, - `bb`, - `bbc`, - `bbt`, - `bbva`, - `bcg`, - `bcn`, - `bd`, - `be`, - `beats`, - `beauty`, - `beer`, - `bentley`, - `berlin`, - `best`, - `bestbuy`, - `bet`, - `bf`, - `bg`, - `bh`, - `bharti`, - `bi`, - `bible`, - `bid`, - `bike`, - `bing`, - `bingo`, - `bio`, - `biz`, - `bj`, - `black`, - `blackfriday`, - `blanco`, - `blockbuster`, - `blog`, - `bloomberg`, - `blue`, - `bm`, - `bms`, - `bmw`, - `bn`, - `bnl`, - `bnpparibas`, - `bo`, - `boats`, - `boehringer`, - `bofa`, - `bom`, - `bond`, - `boo`, - `book`, - `booking`, - `boots`, - `bosch`, - `bostik`, - `boston`, - `bot`, - `boutique`, - `box`, - `br`, - `bradesco`, - `bridgestone`, - `broadway`, - `broker`, - `brother`, - `brussels`, - `bs`, - `bt`, - `budapest`, - `bugatti`, - `build`, - `builders`, - `business`, - `buy`, - `buzz`, - `bv`, - `bw`, - `by`, - `bz`, - `bzh`, - `ca`, - `cab`, - `cafe`, - `cal`, - `call`, - `calvinklein`, - `cam`, - `camera`, - `camp`, - `cancerresearch`, - `canon`, - `capetown`, - `capital`, - `capitalone`, - `car`, - `caravan`, - `cards`, - `care`, - `career`, - `careers`, - `cars`, - `cartier`, - `casa`, - `case`, - `caseih`, - `cash`, - `casino`, - `cat`, - `catering`, - `catholic`, - `cba`, - `cbn`, - `cbre`, - `cbs`, - `cc`, - `cd`, - `ceb`, - `center`, - `ceo`, - `cern`, - `cf`, - `cfa`, - `cfd`, - `cg`, - `ch`, - `chanel`, - `channel`, - `chase`, - `chat`, - `cheap`, - `chintai`, - `chloe`, - `christmas`, - `chrome`, - `chrysler`, - `church`, - `ci`, - `cipriani`, - `circle`, - `cisco`, - `citadel`, - `citi`, - `citic`, - `city`, - `cityeats`, - `ck`, - `cl`, - `claims`, - `cleaning`, - `click`, - `clinic`, - `clinique`, - `clothing`, - `cloud`, - `club`, - `clubmed`, - `cm`, - `cn`, - `co`, - `coach`, - `codes`, - `coffee`, - `college`, - `cologne`, - `com`, - `comcast`, - `commbank`, - `community`, - `company`, - `compare`, - `computer`, - `comsec`, - `condos`, - `construction`, - `consulting`, - `contact`, - `contractors`, - `cooking`, - `cookingchannel`, - `cool`, - `coop`, - `corsica`, - `country`, - `coupon`, - `coupons`, - `courses`, - `cr`, - `credit`, - `creditcard`, - `creditunion`, - `cricket`, - `crown`, - `crs`, - `cruise`, - `cruises`, - `csc`, - `cu`, - `cuisinella`, - `cv`, - `cw`, - `cx`, - `cy`, - `cymru`, - `cyou`, - `cz`, - `dabur`, - `dad`, - `dance`, - `data`, - `date`, - `dating`, - `datsun`, - `day`, - `dclk`, - `dds`, - `de`, - `deal`, - `dealer`, - `deals`, - `degree`, - `delivery`, - `dell`, - `deloitte`, - `delta`, - `democrat`, - `dental`, - `dentist`, - `desi`, - `design`, - `dev`, - `dhl`, - `diamonds`, - `diet`, - `digital`, - `direct`, - `directory`, - `discount`, - `discover`, - `dish`, - `diy`, - `dj`, - `dk`, - `dm`, - `dnp`, - `do`, - `docs`, - `doctor`, - `dodge`, - `dog`, - `doha`, - `domains`, - `dot`, - `download`, - `drive`, - `dtv`, - `dubai`, - `duck`, - `dunlop`, - `duns`, - `dupont`, - `durban`, - `dvag`, - `dvr`, - `dwg`, - `dz`, - `earth`, - `eat`, - `ec`, - `eco`, - `edeka`, - `edu`, - `education`, - `ee`, - `eg`, - `email`, - `emerck`, - `emerson`, - `energy`, - `engineer`, - `engineering`, - `enterprises`, - `epost`, - `epson`, - `equipment`, - `er`, - `ericsson`, - `erni`, - `es`, - `esq`, - `estate`, - `esurance`, - `et`, - `etisalat`, - `eu`, - `eurovision`, - `eus`, - `events`, - `everbank`, - `exchange`, - `expert`, - `exposed`, - `express`, - `extraspace`, - `fage`, - `fail`, - `fairwinds`, - `faith`, - `family`, - `fan`, - `fans`, - `farm`, - `farmers`, - `fashion`, - `fast`, - `fedex`, - `feedback`, - `ferrari`, - `ferrero`, - `fi`, - `fiat`, - `fidelity`, - `fido`, - `film`, - `final`, - `finance`, - `financial`, - `fire`, - `firestone`, - `firmdale`, - `fish`, - `fishing`, - `fit`, - `fitness`, - `fj`, - `fk`, - `flickr`, - `flights`, - `flir`, - `florist`, - `flowers`, - `fly`, - `fm`, - `fo`, - `foo`, - `food`, - `foodnetwork`, - `football`, - `ford`, - `forex`, - `forsale`, - `forum`, - `foundation`, - `fox`, - `fr`, - `free`, - `fresenius`, - `frl`, - `frogans`, - `frontdoor`, - `frontier`, - `ftr`, - `fujitsu`, - `fujixerox`, - `fun`, - `fund`, - `furniture`, - `futbol`, - `fyi`, - `ga`, - `gal`, - `gallery`, - `gallo`, - `gallup`, - `game`, - `games`, - `gap`, - `garden`, - `gb`, - `gbiz`, - `gd`, - `gdn`, - `ge`, - `gea`, - `gent`, - `genting`, - `george`, - `gf`, - `gg`, - `ggee`, - `gh`, - `gi`, - `gift`, - `gifts`, - `gives`, - `giving`, - `gl`, - `glade`, - `glass`, - `gle`, - `global`, - `globo`, - `gm`, - `gmail`, - `gmbh`, - `gmo`, - `gmx`, - `gn`, - `godaddy`, - `gold`, - `goldpoint`, - `golf`, - `goo`, - `goodhands`, - `goodyear`, - `goog`, - `google`, - `gop`, - `got`, - `gov`, - `gp`, - `gq`, - `gr`, - `grainger`, - `graphics`, - `gratis`, - `green`, - `gripe`, - `grocery`, - `group`, - `gs`, - `gt`, - `gu`, - `guardian`, - `gucci`, - `guge`, - `guide`, - `guitars`, - `guru`, - `gw`, - `gy`, - `hair`, - `hamburg`, - `hangout`, - `haus`, - `hbo`, - `hdfc`, - `hdfcbank`, - `health`, - `healthcare`, - `help`, - `helsinki`, - `here`, - `hermes`, - `hgtv`, - `hiphop`, - `hisamitsu`, - `hitachi`, - `hiv`, - `hk`, - `hkt`, - `hm`, - `hn`, - `hockey`, - `holdings`, - `holiday`, - `homedepot`, - `homegoods`, - `homes`, - `homesense`, - `honda`, - `honeywell`, - `horse`, - `host`, - `hosting`, - `hot`, - `hoteles`, - `hotels`, - `hotmail`, - `house`, - `how`, - `hr`, - `hsbc`, - `ht`, - `htc`, - `hu`, - `hughes`, - `hyatt`, - `hyundai`, - `ibm`, - `icbc`, - `ice`, - `icu`, - `id`, - `ie`, - `ieee`, - `ifm`, - `iinet`, - `ikano`, - `il`, - `im`, - `imamat`, - `imdb`, - `immo`, - `immobilien`, - `in`, - `industries`, - `infiniti`, - `info`, - `ing`, - `ink`, - `institute`, - `insurance`, - `insure`, - `int`, - `intel`, - `international`, - `intuit`, - `investments`, - `io`, - `ipiranga`, - `iq`, - `ir`, - `irish`, - `is`, - `iselect`, - `ismaili`, - `ist`, - `istanbul`, - `it`, - `itau`, - `itv`, - `iveco`, - `iwc`, - `jaguar`, - `java`, - `jcb`, - `jcp`, - `je`, - `jeep`, - `jetzt`, - `jewelry`, - `jio`, - `jlc`, - `jll`, - `jm`, - `jmp`, - `jnj`, - `jo`, - `jobs`, - `joburg`, - `jot`, - `joy`, - `jp`, - `jpmorgan`, - `jprs`, - `juegos`, - `juniper`, - `kaufen`, - `kddi`, - `ke`, - `kerryhotels`, - `kerrylogistics`, - `kerryproperties`, - `kfh`, - `kg`, - `kh`, - `ki`, - `kia`, - `kim`, - `kinder`, - `kindle`, - `kitchen`, - `kiwi`, - `km`, - `kn`, - `koeln`, - `komatsu`, - `kosher`, - `kp`, - `kpmg`, - `kpn`, - `kr`, - `krd`, - `kred`, - `kuokgroup`, - `kw`, - `ky`, - `kyoto`, - `kz`, - `la`, - `lacaixa`, - `ladbrokes`, - `lamborghini`, - `lamer`, - `lancaster`, - `lancia`, - `lancome`, - `land`, - `landrover`, - `lanxess`, - `lasalle`, - `lat`, - `latino`, - `latrobe`, - `law`, - `lawyer`, - `lb`, - `lc`, - `lds`, - `lease`, - `leclerc`, - `lefrak`, - `legal`, - `lego`, - `lexus`, - `lgbt`, - `li`, - `liaison`, - `lidl`, - `life`, - `lifeinsurance`, - `lifestyle`, - `lighting`, - `like`, - `lilly`, - `limited`, - `limo`, - `lincoln`, - `linde`, - `link`, - `lipsy`, - `live`, - `living`, - `lixil`, - `lk`, - `loan`, - `loans`, - `locker`, - `locus`, - `loft`, - `lol`, - `london`, - `lotte`, - `lotto`, - `love`, - `lpl`, - `lplfinancial`, - `lr`, - `ls`, - `lt`, - `ltd`, - `ltda`, - `lu`, - `lundbeck`, - `lupin`, - `luxe`, - `luxury`, - `lv`, - `ly`, - `ma`, - `macys`, - `madrid`, - `maif`, - `maison`, - `makeup`, - `man`, - `management`, - `mango`, - `map`, - `market`, - `marketing`, - `markets`, - `marriott`, - `marshalls`, - `maserati`, - `mattel`, - `mba`, - `mc`, - `mcd`, - `mcdonalds`, - `mckinsey`, - `md`, - `me`, - `med`, - `media`, - `meet`, - `melbourne`, - `meme`, - `memorial`, - `men`, - `menu`, - `meo`, - `merckmsd`, - `metlife`, - `mg`, - `mh`, - `miami`, - `microsoft`, - `mil`, - `mini`, - `mint`, - `mit`, - `mitsubishi`, - `mk`, - `ml`, - `mlb`, - `mls`, - `mm`, - `mma`, - `mn`, - `mo`, - `mobi`, - `mobile`, - `mobily`, - `moda`, - `moe`, - `moi`, - `mom`, - `monash`, - `money`, - `monster`, - `montblanc`, - `mopar`, - `mormon`, - `mortgage`, - `moscow`, - `moto`, - `motorcycles`, - `mov`, - `movie`, - `movistar`, - `mp`, - `mq`, - `mr`, - `ms`, - `msd`, - `mt`, - `mtn`, - `mtpc`, - `mtr`, - `mu`, - `museum`, - `mutual`, - `mutuelle`, - `mv`, - `mw`, - `mx`, - `my`, - `mz`, - `na`, - `nab`, - `nadex`, - `nagoya`, - `name`, - `nationwide`, - `natura`, - `navy`, - `nba`, - `nc`, - `ne`, - `nec`, - `net`, - `netbank`, - `netflix`, - `network`, - `neustar`, - `new`, - `newholland`, - `news`, - `next`, - `nextdirect`, - `nexus`, - `nf`, - `nfl`, - `ng`, - `ngo`, - `nhk`, - `ni`, - `nico`, - `nike`, - `nikon`, - `ninja`, - `nissan`, - `nissay`, - `nl`, - `no`, - `nokia`, - `northwesternmutual`, - `norton`, - `now`, - `nowruz`, - `nowtv`, - `np`, - `nr`, - `nra`, - `nrw`, - `ntt`, - `nu`, - `nyc`, - `nz`, - `obi`, - `observer`, - `off`, - `office`, - `okinawa`, - `olayan`, - `olayangroup`, - `oldnavy`, - `ollo`, - `om`, - `omega`, - `one`, - `ong`, - `onl`, - `online`, - `onyourside`, - `ooo`, - `open`, - `oracle`, - `orange`, - `org`, - `organic`, - `orientexpress`, - `origins`, - `osaka`, - `otsuka`, - `ott`, - `ovh`, - `pa`, - `page`, - `pamperedchef`, - `panasonic`, - `panerai`, - `paris`, - `pars`, - `partners`, - `parts`, - `party`, - `passagens`, - `pay`, - `pccw`, - `pe`, - `pet`, - `pf`, - `pfizer`, - `pg`, - `ph`, - `pharmacy`, - `phd`, - `philips`, - `phone`, - `photo`, - `photography`, - `photos`, - `physio`, - `piaget`, - `pics`, - `pictet`, - `pictures`, - `pid`, - `pin`, - `ping`, - `pink`, - `pioneer`, - `pizza`, - `pk`, - `pl`, - `place`, - `play`, - `playstation`, - `plumbing`, - `plus`, - `pm`, - `pn`, - `pnc`, - `pohl`, - `poker`, - `politie`, - `porn`, - `post`, - `pr`, - `pramerica`, - `praxi`, - `press`, - `prime`, - `pro`, - `prod`, - `productions`, - `prof`, - `progressive`, - `promo`, - `properties`, - `property`, - `protection`, - `pru`, - `prudential`, - `ps`, - `pt`, - `pub`, - `pw`, - `pwc`, - `py`, - `qa`, - `qpon`, - `quebec`, - `quest`, - `qvc`, - `racing`, - `radio`, - `raid`, - `re`, - `read`, - `realestate`, - `realtor`, - `realty`, - `recipes`, - `red`, - `redstone`, - `redumbrella`, - `rehab`, - `reise`, - `reisen`, - `reit`, - `reliance`, - `ren`, - `rent`, - `rentals`, - `repair`, - `report`, - `republican`, - `rest`, - `restaurant`, - `review`, - `reviews`, - `rexroth`, - `rich`, - `richardli`, - `ricoh`, - `rightathome`, - `ril`, - `rio`, - `rip`, - `rmit`, - `ro`, - `rocher`, - `rocks`, - `rodeo`, - `rogers`, - `room`, - `rs`, - `rsvp`, - `ru`, - `ruhr`, - `run`, - `rw`, - `rwe`, - `ryukyu`, - `sa`, - `saarland`, - `safe`, - `safety`, - `sakura`, - `sale`, - `salon`, - `samsclub`, - `samsung`, - `sandvik`, - `sandvikcoromant`, - `sanofi`, - `sap`, - `sapo`, - `sarl`, - `sas`, - `save`, - `saxo`, - `sb`, - `sbi`, - `sbs`, - `sc`, - `sca`, - `scb`, - `schaeffler`, - `schmidt`, - `scholarships`, - `school`, - `schule`, - `schwarz`, - `science`, - `scjohnson`, - `scor`, - `scot`, - `sd`, - `se`, - `search`, - `seat`, - `secure`, - `security`, - `seek`, - `select`, - `sener`, - `services`, - `ses`, - `seven`, - `sew`, - `sex`, - `sexy`, - `sfr`, - `sg`, - `sh`, - `shangrila`, - `sharp`, - `shaw`, - `shell`, - `shia`, - `shiksha`, - `shoes`, - `shop`, - `shopping`, - `shouji`, - `show`, - `showtime`, - `shriram`, - `si`, - `silk`, - `sina`, - `singles`, - `site`, - `sj`, - `sk`, - `ski`, - `skin`, - `sky`, - `skype`, - `sl`, - `sling`, - `sm`, - `smart`, - `smile`, - `sn`, - `sncf`, - `so`, - `soccer`, - `social`, - `softbank`, - `software`, - `sohu`, - `solar`, - `solutions`, - `song`, - `sony`, - `soy`, - `space`, - `spiegel`, - `spot`, - `spreadbetting`, - `sr`, - `srl`, - `srt`, - `st`, - `stada`, - `staples`, - `star`, - `starhub`, - `statebank`, - `statefarm`, - `statoil`, - `stc`, - `stcgroup`, - `stockholm`, - `storage`, - `store`, - `stream`, - `studio`, - `study`, - `style`, - `su`, - `sucks`, - `supplies`, - `supply`, - `support`, - `surf`, - `surgery`, - `suzuki`, - `sv`, - `swatch`, - `swiftcover`, - `swiss`, - `sx`, - `sy`, - `sydney`, - `symantec`, - `systems`, - `sz`, - `tab`, - `taipei`, - `talk`, - `taobao`, - `target`, - `tatamotors`, - `tatar`, - `tattoo`, - `tax`, - `taxi`, - `tc`, - `tci`, - `td`, - `tdk`, - `team`, - `tech`, - `technology`, - `tel`, - `telecity`, - `telefonica`, - `temasek`, - `tennis`, - `teva`, - `tf`, - `tg`, - `th`, - `thd`, - `theater`, - `theatre`, - `theguardian`, - `tiaa`, - `tickets`, - `tienda`, - `tiffany`, - `tips`, - `tires`, - `tirol`, - `tj`, - `tjmaxx`, - `tjx`, - `tk`, - `tkmaxx`, - `tl`, - `tm`, - `tmall`, - `tn`, - `to`, - `today`, - `tokyo`, - `tools`, - `top`, - `toray`, - `toshiba`, - `total`, - `tours`, - `town`, - `toyota`, - `toys`, - `tr`, - `trade`, - `trading`, - `training`, - `travel`, - `travelchannel`, - `travelers`, - `travelersinsurance`, - `trust`, - `trv`, - `tt`, - `tube`, - `tui`, - `tunes`, - `tushu`, - `tv`, - `tvs`, - `tw`, - `tz`, - `ua`, - `ubank`, - `ubs`, - `uconnect`, - `ug`, - `uk`, - `unicom`, - `university`, - `uno`, - `uol`, - `ups`, - `us`, - `uy`, - `uz`, - `va`, - `vacations`, - `vana`, - `vanguard`, - `vc`, - `ve`, - `vegas`, - `ventures`, - `verisign`, - `vermögensberater`, - `vermögensberatung`, - `versicherung`, - `vet`, - `vg`, - `vi`, - `viajes`, - `video`, - `vig`, - `viking`, - `villas`, - `vin`, - `vip`, - `virgin`, - `visa`, - `vision`, - `vista`, - `vistaprint`, - `viva`, - `vivo`, - `vlaanderen`, - `vn`, - `vodka`, - `volkswagen`, - `volvo`, - `vote`, - `voting`, - `voto`, - `voyage`, - `vu`, - `vuelos`, - `wales`, - `walmart`, - `walter`, - `wang`, - `wanggou`, - `warman`, - `watch`, - `watches`, - `weather`, - `weatherchannel`, - `webcam`, - `weber`, - `website`, - `wed`, - `wedding`, - `weibo`, - `weir`, - `wf`, - `whoswho`, - `wien`, - `wiki`, - `williamhill`, - `win`, - `windows`, - `wine`, - `winners`, - `wme`, - `wolterskluwer`, - `woodside`, - `work`, - `works`, - `world`, - `wow`, - `ws`, - `wtc`, - `wtf`, - `xbox`, - `xerox`, - `xfinity`, - `xihuan`, - `xin`, - `xperia`, - `xxx`, - `xyz`, - `yachts`, - `yahoo`, - `yamaxun`, - `yandex`, - `ye`, - `yodobashi`, - `yoga`, - `yokohama`, - `you`, - `youtube`, - `yt`, - `yun`, - `za`, - `zappos`, - `zara`, - `zero`, - `zip`, - `zippo`, - `zm`, - `zone`, - `zuerich`, - `zw`, - `ελ`, - `бел`, - `дети`, - `ею`, - `католик`, - `ком`, - `мкд`, - `мон`, - `москва`, - `онлайн`, - `орг`, - `рус`, - `рф`, - `сайт`, - `срб`, - `укр`, - `қаз`, - `հայ`, - `קום`, - `ابوظبي`, - `اتصالات`, - `ارامكو`, - `الاردن`, - `الجزائر`, - `السعودية`, - `السعوديه`, - `السعودیة`, - `السعودیۃ`, - `العليان`, - `المغرب`, - `اليمن`, - `امارات`, - `ايران`, - `ایران`, - `بازار`, - `بيتك`, - `بھارت`, - `تونس`, - `سودان`, - `سوريا`, - `سورية`, - `شبكة`, - `عراق`, - `عرب`, - `عمان`, - `فلسطين`, - `قطر`, - `كاثوليك`, - `كوم`, - `مصر`, - `مليسيا`, - `موبايلي`, - `موقع`, - `همراه`, - `پاكستان`, - `پاکستان`, - `कॉम`, - `नेट`, - `भारत`, - `संगठन`, - `বাংলা`, - `ভারত`, - `ਭਾਰਤ`, - `ભારત`, - `இந்தியா`, - `இலங்கை`, - `சிங்கப்பூர்`, - `భారత్`, - `ලංකා`, - `คอม`, - `ไทย`, - `გე`, - `みんな`, - `クラウド`, - `グーグル`, - `コム`, - `ストア`, - `セール`, - `ファッション`, - `ポイント`, - `一号店`, - `世界`, - `中信`, - `中国`, - `中國`, - `中文网`, - `企业`, - `佛山`, - `信息`, - `健康`, - `八卦`, - `公司`, - `公益`, - `台湾`, - `台灣`, - `商城`, - `商店`, - `商标`, - `嘉里`, - `嘉里大酒店`, - `在线`, - `大众汽车`, - `大拿`, - `天主教`, - `娱乐`, - `家電`, - `工行`, - `广东`, - `微博`, - `慈善`, - `我爱你`, - `手机`, - `手表`, - `政务`, - `政府`, - `新加坡`, - `新闻`, - `时尚`, - `書籍`, - `机构`, - `淡马锡`, - `游戏`, - `澳門`, - `澳门`, - `点看`, - `珠宝`, - `移动`, - `组织机构`, - `网址`, - `网店`, - `网站`, - `网络`, - `联通`, - `臺灣`, - `诺基亚`, - `谷歌`, - `购物`, - `通販`, - `集团`, - `電訊盈科`, - `飞利浦`, - `食品`, - `餐厅`, - `香格里拉`, - `香港`, - `닷넷`, - `닷컴`, - `삼성`, - `한국`, -} diff --git a/vendor/github.com/mvdan/xurls/tlds_pseudo.go b/vendor/github.com/mvdan/xurls/tlds_pseudo.go deleted file mode 100644 index 4183bd5..0000000 --- a/vendor/github.com/mvdan/xurls/tlds_pseudo.go +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright (c) 2015, Daniel Martí -// See LICENSE for licensing information - -package xurls - -// PseudoTLDs is a sorted list of some widely used unofficial TLDs. -// -// Sources: -// * https://en.wikipedia.org/wiki/Pseudo-top-level_domain -// * https://en.wikipedia.org/wiki/Category:Pseudo-top-level_domains -// * https://tools.ietf.org/html/draft-grothoff-iesg-special-use-p2p-names-00 -// * https://www.iana.org/assignments/special-use-domain-names/special-use-domain-names.xhtml -var PseudoTLDs = []string{ - `bit`, // Namecoin - `example`, // Example domain - `exit`, // Tor exit node - `gnu`, // GNS by public key - `i2p`, // I2P network - `invalid`, // Invalid domain - `local`, // Local network - `localhost`, // Local network - `onion`, // Tor hidden services - `test`, // Test domain - `zkey`, // GNS domain name -} diff --git a/vendor/github.com/mvdan/xurls/xurls.go b/vendor/github.com/mvdan/xurls/xurls.go deleted file mode 100644 index 6a99b5d..0000000 --- a/vendor/github.com/mvdan/xurls/xurls.go +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright (c) 2015, Daniel Martí -// See LICENSE for licensing information - -// Package xurls extracts urls from plain text using regular expressions. -package xurls - -import "regexp" - -//go:generate go run generate/tldsgen/main.go -//go:generate go run generate/regexgen/main.go - -const ( - letter = `\p{L}` - number = `\p{N}` - iriChar = letter + number - currency = `\p{Sc}` - otherSymb = `\p{So}` - endChar = iriChar + `/\-+_&~*%=#` + currency + otherSymb - midChar = endChar + `@.,:;'?!|` - wellParen = `\([` + midChar + `]*(\([` + midChar + `]*\)[` + midChar + `]*)*\)` - wellBrack = `\[[` + midChar + `]*(\[[` + midChar + `]*\][` + midChar + `]*)*\]` - wellBrace = `\{[` + midChar + `]*(\{[` + midChar + `]*\}[` + midChar + `]*)*\}` - wellAll = wellParen + `|` + wellBrack + `|` + wellBrace - pathCont = `([` + midChar + `]*(` + wellAll + `|[` + endChar + `])+)+` - comScheme = `[a-zA-Z][a-zA-Z.\-+]*://` - scheme = `(` + comScheme + `|` + otherScheme + `)` - - iri = `[` + iriChar + `]([` + iriChar + `\-]*[` + iriChar + `])?` - domain = `(` + iri + `\.)+` - octet = `(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])` - ipv4Addr = `\b` + octet + `\.` + octet + `\.` + octet + `\.` + octet + `\b` - ipv6Addr = `([0-9a-fA-F]{1,4}:([0-9a-fA-F]{1,4}:([0-9a-fA-F]{1,4}:([0-9a-fA-F]{1,4}:([0-9a-fA-F]{1,4}:[0-9a-fA-F]{0,4}|:[0-9a-fA-F]{1,4})?|(:[0-9a-fA-F]{1,4}){0,2})|(:[0-9a-fA-F]{1,4}){0,3})|(:[0-9a-fA-F]{1,4}){0,4})|:(:[0-9a-fA-F]{1,4}){0,5})((:[0-9a-fA-F]{1,4}){2}|:(25[0-5]|(2[0-4]|1[0-9]|[1-9])?[0-9])(\.(25[0-5]|(2[0-4]|1[0-9]|[1-9])?[0-9])){3})|(([0-9a-fA-F]{1,4}:){1,6}|:):[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){7}:` - ipAddr = `(` + ipv4Addr + `|` + ipv6Addr + `)` - site = domain + gtld - hostName = `(` + site + `|` + ipAddr + `)` - port = `(:[0-9]*)?` - path = `(/|/` + pathCont + `?|\b|$)` - webURL = hostName + port + path - - strict = `(\b` + scheme + pathCont + `)` - relaxed = `(` + strict + `|` + webURL + `)` -) - -var ( - // Relaxed matches all the urls it can find. - Relaxed = regexp.MustCompile(relaxed) - // Strict only matches urls with a scheme to avoid false positives. - Strict = regexp.MustCompile(strict) -) - -func init() { - Relaxed.Longest() - Strict.Longest() -} - -// StrictMatchingScheme produces a regexp that matches urls like Strict but -// whose scheme matches the given regular expression. -func StrictMatchingScheme(exp string) (*regexp.Regexp, error) { - strictMatching := `(\b(?i)(` + exp + `)(?-i)` + pathCont + `)` - re, err := regexp.Compile(strictMatching) - if err != nil { - return nil, err - } - re.Longest() - return re, nil -} diff --git a/vendor/github.com/olekukonko/tablewriter/LICENCE.md b/vendor/github.com/olekukonko/tablewriter/LICENCE.md new file mode 100644 index 0000000..1fd8484 --- /dev/null +++ b/vendor/github.com/olekukonko/tablewriter/LICENCE.md @@ -0,0 +1,19 @@ +Copyright (C) 2014 by Oleku Konko + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. \ No newline at end of file diff --git a/vendor/github.com/olekukonko/tablewriter/README.md b/vendor/github.com/olekukonko/tablewriter/README.md new file mode 100644 index 0000000..833ab30 --- /dev/null +++ b/vendor/github.com/olekukonko/tablewriter/README.md @@ -0,0 +1,204 @@ +ASCII Table Writer +========= + +[![Build Status](https://travis-ci.org/olekukonko/tablewriter.png?branch=master)](https://travis-ci.org/olekukonko/tablewriter) [![Total views](https://sourcegraph.com/api/repos/github.com/olekukonko/tablewriter/counters/views.png)](https://sourcegraph.com/github.com/olekukonko/tablewriter) + +Generate ASCII table on the fly ... Installation is simple as + + go get github.com/olekukonko/tablewriter + + +#### Features +- Automatic Padding +- Support Multiple Lines +- Supports Alignment +- Support Custom Separators +- Automatic Alignment of numbers & percentage +- Write directly to http , file etc via `io.Writer` +- Read directly from CSV file +- Optional row line via `SetRowLine` +- Normalise table header +- Make CSV Headers optional +- Enable or disable table border +- Set custom footer support +- Optional identical cells merging + + +#### Example 1 - Basic +```go +data := [][]string{ + []string{"A", "The Good", "500"}, + []string{"B", "The Very very Bad Man", "288"}, + []string{"C", "The Ugly", "120"}, + []string{"D", "The Gopher", "800"}, +} + +table := tablewriter.NewWriter(os.Stdout) +table.SetHeader([]string{"Name", "Sign", "Rating"}) + +for _, v := range data { + table.Append(v) +} +table.Render() // Send output +``` + +##### Output 1 +``` ++------+-----------------------+--------+ +| NAME | SIGN | RATING | ++------+-----------------------+--------+ +| A | The Good | 500 | +| B | The Very very Bad Man | 288 | +| C | The Ugly | 120 | +| D | The Gopher | 800 | ++------+-----------------------+--------+ +``` + +#### Example 2 - Without Border / Footer / Bulk Append +```go +data := [][]string{ + []string{"1/1/2014", "Domain name", "2233", "$10.98"}, + []string{"1/1/2014", "January Hosting", "2233", "$54.95"}, + []string{"1/4/2014", "February Hosting", "2233", "$51.00"}, + []string{"1/4/2014", "February Extra Bandwidth", "2233", "$30.00"}, +} + +table := tablewriter.NewWriter(os.Stdout) +table.SetHeader([]string{"Date", "Description", "CV2", "Amount"}) +table.SetFooter([]string{"", "", "Total", "$146.93"}) // Add Footer +table.SetBorder(false) // Set Border to false +table.AppendBulk(data) // Add Bulk Data +table.Render() +``` + +##### Output 2 +``` + + DATE | DESCRIPTION | CV2 | AMOUNT ++----------+--------------------------+-------+---------+ + 1/1/2014 | Domain name | 2233 | $10.98 + 1/1/2014 | January Hosting | 2233 | $54.95 + 1/4/2014 | February Hosting | 2233 | $51.00 + 1/4/2014 | February Extra Bandwidth | 2233 | $30.00 ++----------+--------------------------+-------+---------+ + TOTAL | $146 93 + +-------+---------+ + +``` + + +#### Example 3 - CSV +```go +table, _ := tablewriter.NewCSV(os.Stdout, "test_info.csv", true) +table.SetAlignment(tablewriter.ALIGN_LEFT) // Set Alignment +table.Render() +``` + +##### Output 3 +``` ++----------+--------------+------+-----+---------+----------------+ +| FIELD | TYPE | NULL | KEY | DEFAULT | EXTRA | ++----------+--------------+------+-----+---------+----------------+ +| user_id | smallint(5) | NO | PRI | NULL | auto_increment | +| username | varchar(10) | NO | | NULL | | +| password | varchar(100) | NO | | NULL | | ++----------+--------------+------+-----+---------+----------------+ +``` + +#### Example 4 - Custom Separator +```go +table, _ := tablewriter.NewCSV(os.Stdout, "test.csv", true) +table.SetRowLine(true) // Enable row line + +// Change table lines +table.SetCenterSeparator("*") +table.SetColumnSeparator("‡") +table.SetRowSeparator("-") + +table.SetAlignment(tablewriter.ALIGN_LEFT) +table.Render() +``` + +##### Output 4 +``` +*------------*-----------*---------* +╪ FIRST NAME ╪ LAST NAME ╪ SSN ╪ +*------------*-----------*---------* +╪ John ╪ Barry ╪ 123456 ╪ +*------------*-----------*---------* +╪ Kathy ╪ Smith ╪ 687987 ╪ +*------------*-----------*---------* +╪ Bob ╪ McCornick ╪ 3979870 ╪ +*------------*-----------*---------* +``` + +##### Example 5 - Markdown Format +```go +data := [][]string{ + []string{"1/1/2014", "Domain name", "2233", "$10.98"}, + []string{"1/1/2014", "January Hosting", "2233", "$54.95"}, + []string{"1/4/2014", "February Hosting", "2233", "$51.00"}, + []string{"1/4/2014", "February Extra Bandwidth", "2233", "$30.00"}, +} + +table := tablewriter.NewWriter(os.Stdout) +table.SetHeader([]string{"Date", "Description", "CV2", "Amount"}) +table.SetBorders(tablewriter.Border{Left: true, Top: false, Right: true, Bottom: false}) +table.SetCenterSeparator("|") +table.AppendBulk(data) // Add Bulk Data +table.Render() +``` + +##### Output 5 +``` +| DATE | DESCRIPTION | CV2 | AMOUNT | +|----------|--------------------------|------|--------| +| 1/1/2014 | Domain name | 2233 | $10.98 | +| 1/1/2014 | January Hosting | 2233 | $54.95 | +| 1/4/2014 | February Hosting | 2233 | $51.00 | +| 1/4/2014 | February Extra Bandwidth | 2233 | $30.00 | +``` + +#### Example 6 - Identical cells merging +```go +data := [][]string{ + []string{"1/1/2014", "Domain name", "1234", "$10.98"}, + []string{"1/1/2014", "January Hosting", "2345", "$54.95"}, + []string{"1/4/2014", "February Hosting", "3456", "$51.00"}, + []string{"1/4/2014", "February Extra Bandwidth", "4567", "$30.00"}, +} + +table := NewWriter(os.Stdout) +table.SetHeader([]string{"Date", "Description", "CV2", "Amount"}) +table.SetFooter([]string{"", "", "Total", "$146.93"}) +table.SetAutoMergeCells(true) +table.SetRowLine(true) +table.AppendBulk(data) +table.Render() +``` + +##### Output 6 +``` ++----------+--------------------------+-------+---------+ +| DATE | DESCRIPTION | CV2 | AMOUNT | ++----------+--------------------------+-------+---------+ +| 1/1/2014 | Domain name | 1234 | $10.98 | ++ +--------------------------+-------+---------+ +| | January Hosting | 2345 | $54.95 | ++----------+--------------------------+-------+---------+ +| 1/4/2014 | February Hosting | 3456 | $51.00 | ++ +--------------------------+-------+---------+ +| | February Extra Bandwidth | 4567 | $30.00 | ++----------+--------------------------+-------+---------+ +| TOTAL | $146 93 | ++----------+--------------------------+-------+---------+ +``` + +#### TODO +- ~~Import Directly from CSV~~ - `done` +- ~~Support for `SetFooter`~~ - `done` +- ~~Support for `SetBorder`~~ - `done` +- ~~Support table with uneven rows~~ - `done` +- Support custom alignment +- General Improvement & Optimisation +- `NewHTML` Parse table from HTML diff --git a/vendor/github.com/olekukonko/tablewriter/csv.go b/vendor/github.com/olekukonko/tablewriter/csv.go new file mode 100644 index 0000000..9887830 --- /dev/null +++ b/vendor/github.com/olekukonko/tablewriter/csv.go @@ -0,0 +1,52 @@ +// Copyright 2014 Oleku Konko All rights reserved. +// Use of this source code is governed by a MIT +// license that can be found in the LICENSE file. + +// This module is a Table Writer API for the Go Programming Language. +// The protocols were written in pure Go and works on windows and unix systems + +package tablewriter + +import ( + "encoding/csv" + "io" + "os" +) + +// Start A new table by importing from a CSV file +// Takes io.Writer and csv File name +func NewCSV(writer io.Writer, fileName string, hasHeader bool) (*Table, error) { + file, err := os.Open(fileName) + if err != nil { + return &Table{}, err + } + defer file.Close() + csvReader := csv.NewReader(file) + t, err := NewCSVReader(writer, csvReader, hasHeader) + return t, err +} + +// Start a New Table Writer with csv.Reader +// This enables customisation such as reader.Comma = ';' +// See http://golang.org/src/pkg/encoding/csv/reader.go?s=3213:3671#L94 +func NewCSVReader(writer io.Writer, csvReader *csv.Reader, hasHeader bool) (*Table, error) { + t := NewWriter(writer) + if hasHeader { + // Read the first row + headers, err := csvReader.Read() + if err != nil { + return &Table{}, err + } + t.SetHeader(headers) + } + for { + record, err := csvReader.Read() + if err == io.EOF { + break + } else if err != nil { + return &Table{}, err + } + t.Append(record) + } + return t, nil +} diff --git a/vendor/github.com/olekukonko/tablewriter/table.go b/vendor/github.com/olekukonko/tablewriter/table.go new file mode 100644 index 0000000..3314bfb --- /dev/null +++ b/vendor/github.com/olekukonko/tablewriter/table.go @@ -0,0 +1,662 @@ +// Copyright 2014 Oleku Konko All rights reserved. +// Use of this source code is governed by a MIT +// license that can be found in the LICENSE file. + +// This module is a Table Writer API for the Go Programming Language. +// The protocols were written in pure Go and works on windows and unix systems + +// Create & Generate text based table +package tablewriter + +import ( + "bytes" + "fmt" + "io" + "regexp" + "strings" +) + +const ( + MAX_ROW_WIDTH = 30 +) + +const ( + CENTER = "+" + ROW = "-" + COLUMN = "|" + SPACE = " " + NEWLINE = "\n" +) + +const ( + ALIGN_DEFAULT = iota + ALIGN_CENTER + ALIGN_RIGHT + ALIGN_LEFT +) + +var ( + decimal = regexp.MustCompile(`^-*\d*\.?\d*$`) + percent = regexp.MustCompile(`^-*\d*\.?\d*$%$`) +) + +type Border struct { + Left bool + Right bool + Top bool + Bottom bool +} + +type Table struct { + out io.Writer + rows [][]string + lines [][][]string + cs map[int]int + rs map[int]int + headers []string + footers []string + autoFmt bool + autoWrap bool + mW int + pCenter string + pRow string + pColumn string + tColumn int + tRow int + hAlign int + fAlign int + align int + newLine string + rowLine bool + autoMergeCells bool + hdrLine bool + borders Border + colSize int +} + +// Start New Table +// Take io.Writer Directly +func NewWriter(writer io.Writer) *Table { + t := &Table{ + out: writer, + rows: [][]string{}, + lines: [][][]string{}, + cs: make(map[int]int), + rs: make(map[int]int), + headers: []string{}, + footers: []string{}, + autoFmt: true, + autoWrap: true, + mW: MAX_ROW_WIDTH, + pCenter: CENTER, + pRow: ROW, + pColumn: COLUMN, + tColumn: -1, + tRow: -1, + hAlign: ALIGN_DEFAULT, + fAlign: ALIGN_DEFAULT, + align: ALIGN_DEFAULT, + newLine: NEWLINE, + rowLine: false, + hdrLine: true, + borders: Border{Left: true, Right: true, Bottom: true, Top: true}, + colSize: -1} + return t +} + +// Render table output +func (t Table) Render() { + if t.borders.Top { + t.printLine(true) + } + t.printHeading() + if t.autoMergeCells { + t.printRowsMergeCells() + } else { + t.printRows() + } + + if !t.rowLine && t.borders.Bottom { + t.printLine(true) + } + t.printFooter() + +} + +// Set table header +func (t *Table) SetHeader(keys []string) { + t.colSize = len(keys) + for i, v := range keys { + t.parseDimension(v, i, -1) + t.headers = append(t.headers, v) + } +} + +// Set table Footer +func (t *Table) SetFooter(keys []string) { + //t.colSize = len(keys) + for i, v := range keys { + t.parseDimension(v, i, -1) + t.footers = append(t.footers, v) + } +} + +// Turn header autoformatting on/off. Default is on (true). +func (t *Table) SetAutoFormatHeaders(auto bool) { + t.autoFmt = auto +} + +// Turn automatic multiline text adjustment on/off. Default is on (true). +func (t *Table) SetAutoWrapText(auto bool) { + t.autoWrap = auto +} + +// Set the Default column width +func (t *Table) SetColWidth(width int) { + t.mW = width +} + +// Set the Column Separator +func (t *Table) SetColumnSeparator(sep string) { + t.pColumn = sep +} + +// Set the Row Separator +func (t *Table) SetRowSeparator(sep string) { + t.pRow = sep +} + +// Set the center Separator +func (t *Table) SetCenterSeparator(sep string) { + t.pCenter = sep +} + +// Set Header Alignment +func (t *Table) SetHeaderAlignment(hAlign int) { + t.hAlign = hAlign +} + +// Set Footer Alignment +func (t *Table) SetFooterAlignment(fAlign int) { + t.fAlign = fAlign +} + +// Set Table Alignment +func (t *Table) SetAlignment(align int) { + t.align = align +} + +// Set New Line +func (t *Table) SetNewLine(nl string) { + t.newLine = nl +} + +// Set Header Line +// This would enable / disable a line after the header +func (t *Table) SetHeaderLine(line bool) { + t.hdrLine = line +} + +// Set Row Line +// This would enable / disable a line on each row of the table +func (t *Table) SetRowLine(line bool) { + t.rowLine = line +} + +// Set Auto Merge Cells +// This would enable / disable the merge of cells with identical values +func (t *Table) SetAutoMergeCells(auto bool) { + t.autoMergeCells = auto +} + +// Set Table Border +// This would enable / disable line around the table +func (t *Table) SetBorder(border bool) { + t.SetBorders(Border{border, border, border, border}) +} + +func (t *Table) SetBorders(border Border) { + t.borders = border +} + +// Append row to table +func (t *Table) Append(row []string) { + rowSize := len(t.headers) + if rowSize > t.colSize { + t.colSize = rowSize + } + + n := len(t.lines) + line := [][]string{} + for i, v := range row { + + // Detect string width + // Detect String height + // Break strings into words + out := t.parseDimension(v, i, n) + + // Append broken words + line = append(line, out) + } + t.lines = append(t.lines, line) +} + +// Allow Support for Bulk Append +// Eliminates repeated for loops +func (t *Table) AppendBulk(rows [][]string) { + for _, row := range rows { + t.Append(row) + } +} + +// Print line based on row width +func (t Table) printLine(nl bool) { + fmt.Fprint(t.out, t.pCenter) + for i := 0; i < len(t.cs); i++ { + v := t.cs[i] + fmt.Fprintf(t.out, "%s%s%s%s", + t.pRow, + strings.Repeat(string(t.pRow), v), + t.pRow, + t.pCenter) + } + if nl { + fmt.Fprint(t.out, t.newLine) + } +} + +// Print line based on row width with our without cell separator +func (t Table) printLineOptionalCellSeparators(nl bool, displayCellSeparator []bool) { + fmt.Fprint(t.out, t.pCenter) + for i := 0; i < len(t.cs); i++ { + v := t.cs[i] + if i > len(displayCellSeparator) || displayCellSeparator[i] { + // Display the cell separator + fmt.Fprintf(t.out, "%s%s%s%s", + t.pRow, + strings.Repeat(string(t.pRow), v), + t.pRow, + t.pCenter) + } else { + // Don't display the cell separator for this cell + fmt.Fprintf(t.out, "%s%s", + strings.Repeat(" ", v+2), + t.pCenter) + } + } + if nl { + fmt.Fprint(t.out, t.newLine) + } +} + +// Return the PadRight function if align is left, PadLeft if align is right, +// and Pad by default +func pad(align int) func(string, string, int) string { + padFunc := Pad + switch align { + case ALIGN_LEFT: + padFunc = PadRight + case ALIGN_RIGHT: + padFunc = PadLeft + } + return padFunc +} + +// Print heading information +func (t Table) printHeading() { + // Check if headers is available + if len(t.headers) < 1 { + return + } + + // Check if border is set + // Replace with space if not set + fmt.Fprint(t.out, ConditionString(t.borders.Left, t.pColumn, SPACE)) + + // Identify last column + end := len(t.cs) - 1 + + // Get pad function + padFunc := pad(t.hAlign) + + // Print Heading column + for i := 0; i <= end; i++ { + v := t.cs[i] + h := t.headers[i] + if t.autoFmt { + h = Title(h) + } + pad := ConditionString((i == end && !t.borders.Left), SPACE, t.pColumn) + fmt.Fprintf(t.out, " %s %s", + padFunc(h, SPACE, v), + pad) + } + // Next line + fmt.Fprint(t.out, t.newLine) + if t.hdrLine { + t.printLine(true) + } +} + +// Print heading information +func (t Table) printFooter() { + // Check if headers is available + if len(t.footers) < 1 { + return + } + + // Only print line if border is not set + if !t.borders.Bottom { + t.printLine(true) + } + // Check if border is set + // Replace with space if not set + fmt.Fprint(t.out, ConditionString(t.borders.Bottom, t.pColumn, SPACE)) + + // Identify last column + end := len(t.cs) - 1 + + // Get pad function + padFunc := pad(t.fAlign) + + // Print Heading column + for i := 0; i <= end; i++ { + v := t.cs[i] + f := t.footers[i] + if t.autoFmt { + f = Title(f) + } + pad := ConditionString((i == end && !t.borders.Top), SPACE, t.pColumn) + + if len(t.footers[i]) == 0 { + pad = SPACE + } + fmt.Fprintf(t.out, " %s %s", + padFunc(f, SPACE, v), + pad) + } + // Next line + fmt.Fprint(t.out, t.newLine) + //t.printLine(true) + + hasPrinted := false + + for i := 0; i <= end; i++ { + v := t.cs[i] + pad := t.pRow + center := t.pCenter + length := len(t.footers[i]) + + if length > 0 { + hasPrinted = true + } + + // Set center to be space if length is 0 + if length == 0 && !t.borders.Right { + center = SPACE + } + + // Print first junction + if i == 0 { + fmt.Fprint(t.out, center) + } + + // Pad With space of length is 0 + if length == 0 { + pad = SPACE + } + // Ignore left space of it has printed before + if hasPrinted || t.borders.Left { + pad = t.pRow + center = t.pCenter + } + + // Change Center start position + if center == SPACE { + if i < end && len(t.footers[i+1]) != 0 { + center = t.pCenter + } + } + + // Print the footer + fmt.Fprintf(t.out, "%s%s%s%s", + pad, + strings.Repeat(string(pad), v), + pad, + center) + + } + + fmt.Fprint(t.out, t.newLine) + +} + +func (t Table) printRows() { + for i, lines := range t.lines { + t.printRow(lines, i) + } + +} + +// Print Row Information +// Adjust column alignment based on type + +func (t Table) printRow(columns [][]string, colKey int) { + // Get Maximum Height + max := t.rs[colKey] + total := len(columns) + + // TODO Fix uneven col size + // if total < t.colSize { + // for n := t.colSize - total; n < t.colSize ; n++ { + // columns = append(columns, []string{SPACE}) + // t.cs[n] = t.mW + // } + //} + + // Pad Each Height + // pads := []int{} + pads := []int{} + + for i, line := range columns { + length := len(line) + pad := max - length + pads = append(pads, pad) + for n := 0; n < pad; n++ { + columns[i] = append(columns[i], " ") + } + } + //fmt.Println(max, "\n") + for x := 0; x < max; x++ { + for y := 0; y < total; y++ { + + // Check if border is set + fmt.Fprint(t.out, ConditionString((!t.borders.Left && y == 0), SPACE, t.pColumn)) + + fmt.Fprintf(t.out, SPACE) + str := columns[y][x] + + // This would print alignment + // Default alignment would use multiple configuration + switch t.align { + case ALIGN_CENTER: // + fmt.Fprintf(t.out, "%s", Pad(str, SPACE, t.cs[y])) + case ALIGN_RIGHT: + fmt.Fprintf(t.out, "%s", PadLeft(str, SPACE, t.cs[y])) + case ALIGN_LEFT: + fmt.Fprintf(t.out, "%s", PadRight(str, SPACE, t.cs[y])) + default: + if decimal.MatchString(strings.TrimSpace(str)) || percent.MatchString(strings.TrimSpace(str)) { + fmt.Fprintf(t.out, "%s", PadLeft(str, SPACE, t.cs[y])) + } else { + fmt.Fprintf(t.out, "%s", PadRight(str, SPACE, t.cs[y])) + + // TODO Custom alignment per column + //if max == 1 || pads[y] > 0 { + // fmt.Fprintf(t.out, "%s", Pad(str, SPACE, t.cs[y])) + //} else { + // fmt.Fprintf(t.out, "%s", PadRight(str, SPACE, t.cs[y])) + //} + + } + } + fmt.Fprintf(t.out, SPACE) + } + // Check if border is set + // Replace with space if not set + fmt.Fprint(t.out, ConditionString(t.borders.Left, t.pColumn, SPACE)) + fmt.Fprint(t.out, t.newLine) + } + + if t.rowLine { + t.printLine(true) + } +} + +// Print the rows of the table and merge the cells that are identical +func (t Table) printRowsMergeCells() { + var previousLine []string + var displayCellBorder []bool + var tmpWriter bytes.Buffer + for i, lines := range t.lines { + // We store the display of the current line in a tmp writer, as we need to know which border needs to be print above + previousLine, displayCellBorder = t.printRowMergeCells(&tmpWriter, lines, i, previousLine) + if i > 0 { //We don't need to print borders above first line + if t.rowLine { + t.printLineOptionalCellSeparators(true, displayCellBorder) + } + } + tmpWriter.WriteTo(t.out) + } + //Print the end of the table + if t.rowLine { + t.printLine(true) + } +} + +// Print Row Information to a writer and merge identical cells. +// Adjust column alignment based on type + +func (t Table) printRowMergeCells(writer io.Writer, columns [][]string, colKey int, previousLine []string) ([]string, []bool) { + // Get Maximum Height + max := t.rs[colKey] + total := len(columns) + + // Pad Each Height + pads := []int{} + + for i, line := range columns { + length := len(line) + pad := max - length + pads = append(pads, pad) + for n := 0; n < pad; n++ { + columns[i] = append(columns[i], " ") + } + } + + var displayCellBorder []bool + for x := 0; x < max; x++ { + for y := 0; y < total; y++ { + + // Check if border is set + fmt.Fprint(writer, ConditionString((!t.borders.Left && y == 0), SPACE, t.pColumn)) + + fmt.Fprintf(writer, SPACE) + + str := columns[y][x] + + if t.autoMergeCells { + //Store the full line to merge mutli-lines cells + fullLine := strings.Join(columns[y], " ") + if len(previousLine) > y && fullLine == previousLine[y] && fullLine != "" { + // If this cell is identical to the one above but not empty, we don't display the border and keep the cell empty. + displayCellBorder = append(displayCellBorder, false) + str = "" + } else { + // First line or different content, keep the content and print the cell border + displayCellBorder = append(displayCellBorder, true) + } + } + + // This would print alignment + // Default alignment would use multiple configuration + switch t.align { + case ALIGN_CENTER: // + fmt.Fprintf(writer, "%s", Pad(str, SPACE, t.cs[y])) + case ALIGN_RIGHT: + fmt.Fprintf(writer, "%s", PadLeft(str, SPACE, t.cs[y])) + case ALIGN_LEFT: + fmt.Fprintf(writer, "%s", PadRight(str, SPACE, t.cs[y])) + default: + if decimal.MatchString(strings.TrimSpace(str)) || percent.MatchString(strings.TrimSpace(str)) { + fmt.Fprintf(writer, "%s", PadLeft(str, SPACE, t.cs[y])) + } else { + fmt.Fprintf(writer, "%s", PadRight(str, SPACE, t.cs[y])) + } + } + fmt.Fprintf(writer, SPACE) + } + // Check if border is set + // Replace with space if not set + fmt.Fprint(writer, ConditionString(t.borders.Left, t.pColumn, SPACE)) + fmt.Fprint(writer, t.newLine) + } + + //The new previous line is the current one + previousLine = make([]string, total) + for y := 0; y < total; y++ { + previousLine[y] = strings.Join(columns[y], " ") //Store the full line for multi-lines cells + } + //Returns the newly added line and wether or not a border should be displayed above. + return previousLine, displayCellBorder +} + +func (t *Table) parseDimension(str string, colKey, rowKey int) []string { + var ( + raw []string + max int + ) + w := DisplayWidth(str) + // Calculate Width + // Check if with is grater than maximum width + if w > t.mW { + w = t.mW + } + + // Check if width exists + v, ok := t.cs[colKey] + if !ok || v < w || v == 0 { + t.cs[colKey] = w + } + + if rowKey == -1 { + return raw + } + // Calculate Height + if t.autoWrap { + raw, _ = WrapString(str, t.cs[colKey]) + } else { + raw = getLines(str) + } + + for _, line := range raw { + if w := DisplayWidth(line); w > max { + max = w + } + } + + // Make sure the with is the same length as maximum word + // Important for cases where the width is smaller than maxu word + if max > t.cs[colKey] { + t.cs[colKey] = max + } + + h := len(raw) + v, ok = t.rs[rowKey] + + if !ok || v < h || v == 0 { + t.rs[rowKey] = h + } + //fmt.Printf("Raw %+v %d\n", raw, len(raw)) + return raw +} diff --git a/vendor/github.com/olekukonko/tablewriter/test.csv b/vendor/github.com/olekukonko/tablewriter/test.csv new file mode 100644 index 0000000..1609327 --- /dev/null +++ b/vendor/github.com/olekukonko/tablewriter/test.csv @@ -0,0 +1,4 @@ +first_name,last_name,ssn +John,Barry,123456 +Kathy,Smith,687987 +Bob,McCornick,3979870 \ No newline at end of file diff --git a/vendor/github.com/olekukonko/tablewriter/test_info.csv b/vendor/github.com/olekukonko/tablewriter/test_info.csv new file mode 100644 index 0000000..e4c40e9 --- /dev/null +++ b/vendor/github.com/olekukonko/tablewriter/test_info.csv @@ -0,0 +1,4 @@ +Field,Type,Null,Key,Default,Extra +user_id,smallint(5),NO,PRI,NULL,auto_increment +username,varchar(10),NO,,NULL, +password,varchar(100),NO,,NULL, \ No newline at end of file diff --git a/vendor/github.com/olekukonko/tablewriter/util.go b/vendor/github.com/olekukonko/tablewriter/util.go new file mode 100644 index 0000000..2deefbc --- /dev/null +++ b/vendor/github.com/olekukonko/tablewriter/util.go @@ -0,0 +1,72 @@ +// Copyright 2014 Oleku Konko All rights reserved. +// Use of this source code is governed by a MIT +// license that can be found in the LICENSE file. + +// This module is a Table Writer API for the Go Programming Language. +// The protocols were written in pure Go and works on windows and unix systems + +package tablewriter + +import ( + "math" + "regexp" + "strings" + + "github.com/mattn/go-runewidth" +) + +var ansi = regexp.MustCompile("\033\\[(?:[0-9]{1,3}(?:;[0-9]{1,3})*)?[m|K]") + +func DisplayWidth(str string) int { + return runewidth.StringWidth(ansi.ReplaceAllLiteralString(str, "")) +} + +// Simple Condition for string +// Returns value based on condition +func ConditionString(cond bool, valid, inValid string) string { + if cond { + return valid + } + return inValid +} + +// Format Table Header +// Replace _ , . and spaces +func Title(name string) string { + name = strings.Replace(name, "_", " ", -1) + name = strings.Replace(name, ".", " ", -1) + name = strings.TrimSpace(name) + return strings.ToUpper(name) +} + +// Pad String +// Attempts to play string in the center +func Pad(s, pad string, width int) string { + gap := width - DisplayWidth(s) + if gap > 0 { + gapLeft := int(math.Ceil(float64(gap / 2))) + gapRight := gap - gapLeft + return strings.Repeat(string(pad), gapLeft) + s + strings.Repeat(string(pad), gapRight) + } + return s +} + +// Pad String Right position +// This would pace string at the left side fo the screen +func PadRight(s, pad string, width int) string { + gap := width - DisplayWidth(s) + if gap > 0 { + return s + strings.Repeat(string(pad), gap) + } + return s +} + +// Pad String Left position +// This would pace string at the right side fo the screen +func PadLeft(s, pad string, width int) string { + gap := width - DisplayWidth(s) + if gap > 0 { + return strings.Repeat(string(pad), gap) + s + } + return s +} diff --git a/vendor/github.com/olekukonko/tablewriter/wrap.go b/vendor/github.com/olekukonko/tablewriter/wrap.go new file mode 100644 index 0000000..f3747d9 --- /dev/null +++ b/vendor/github.com/olekukonko/tablewriter/wrap.go @@ -0,0 +1,103 @@ +// Copyright 2014 Oleku Konko All rights reserved. +// Use of this source code is governed by a MIT +// license that can be found in the LICENSE file. + +// This module is a Table Writer API for the Go Programming Language. +// The protocols were written in pure Go and works on windows and unix systems + +package tablewriter + +import ( + "math" + "strings" + "unicode/utf8" +) + +var ( + nl = "\n" + sp = " " +) + +const defaultPenalty = 1e5 + +// Wrap wraps s into a paragraph of lines of length lim, with minimal +// raggedness. +func WrapString(s string, lim int) ([]string, int) { + words := strings.Split(strings.Replace(strings.TrimSpace(s), nl, sp, -1), sp) + var lines []string + max := 0 + for _, v := range words { + max = len(v) + if max > lim { + lim = max + } + } + for _, line := range WrapWords(words, 1, lim, defaultPenalty) { + lines = append(lines, strings.Join(line, sp)) + } + return lines, lim +} + +// WrapWords is the low-level line-breaking algorithm, useful if you need more +// control over the details of the text wrapping process. For most uses, +// WrapString will be sufficient and more convenient. +// +// WrapWords splits a list of words into lines with minimal "raggedness", +// treating each rune as one unit, accounting for spc units between adjacent +// words on each line, and attempting to limit lines to lim units. Raggedness +// is the total error over all lines, where error is the square of the +// difference of the length of the line and lim. Too-long lines (which only +// happen when a single word is longer than lim units) have pen penalty units +// added to the error. +func WrapWords(words []string, spc, lim, pen int) [][]string { + n := len(words) + + length := make([][]int, n) + for i := 0; i < n; i++ { + length[i] = make([]int, n) + length[i][i] = utf8.RuneCountInString(words[i]) + for j := i + 1; j < n; j++ { + length[i][j] = length[i][j-1] + spc + utf8.RuneCountInString(words[j]) + } + } + nbrk := make([]int, n) + cost := make([]int, n) + for i := range cost { + cost[i] = math.MaxInt32 + } + for i := n - 1; i >= 0; i-- { + if length[i][n-1] <= lim { + cost[i] = 0 + nbrk[i] = n + } else { + for j := i + 1; j < n; j++ { + d := lim - length[i][j-1] + c := d*d + cost[j] + if length[i][j-1] > lim { + c += pen // too-long lines get a worse penalty + } + if c < cost[i] { + cost[i] = c + nbrk[i] = j + } + } + } + } + var lines [][]string + i := 0 + for i < n { + lines = append(lines, words[i:nbrk[i]]) + i = nbrk[i] + } + return lines +} + +// getLines decomposes a multiline string into a slice of strings. +func getLines(s string) []string { + var lines []string + + for _, line := range strings.Split(strings.TrimSpace(s), nl) { + lines = append(lines, line) + } + return lines +} diff --git a/vendor/github.com/pelletier/go-toml/README.md b/vendor/github.com/pelletier/go-toml/README.md index b511f39..167fa1c 100644 --- a/vendor/github.com/pelletier/go-toml/README.md +++ b/vendor/github.com/pelletier/go-toml/README.md @@ -96,7 +96,7 @@ Go-toml provides two handy command line tools: * `tomljson`: Reads a TOML file and outputs its JSON representation. ``` - go install github.com/pelletier/go-toml/cmd/tomjson + go install github.com/pelletier/go-toml/cmd/tomljson tomljson --help ``` diff --git a/vendor/github.com/pelletier/go-toml/keysparsing.go b/vendor/github.com/pelletier/go-toml/keysparsing.go index b67664f..d62ca5f 100644 --- a/vendor/github.com/pelletier/go-toml/keysparsing.go +++ b/vendor/github.com/pelletier/go-toml/keysparsing.go @@ -4,6 +4,7 @@ package toml import ( "bytes" + "errors" "fmt" "unicode" ) @@ -47,7 +48,7 @@ func parseKey(key string) ([]string, error) { } else { if !wasInQuotes { if buffer.Len() == 0 { - return nil, fmt.Errorf("empty key group") + return nil, errors.New("empty table key") } groups = append(groups, buffer.String()) buffer.Reset() @@ -67,23 +68,23 @@ func parseKey(key string) ([]string, error) { return nil, fmt.Errorf("invalid bare character: %c", char) } if !inQuotes && expectDot { - return nil, fmt.Errorf("what?") + return nil, errors.New("what?") } buffer.WriteRune(char) expectDot = false } } if inQuotes { - return nil, fmt.Errorf("mismatched quotes") + return nil, errors.New("mismatched quotes") } if escapeNext { - return nil, fmt.Errorf("unfinished escape sequence") + return nil, errors.New("unfinished escape sequence") } if buffer.Len() > 0 { groups = append(groups, buffer.String()) } if len(groups) == 0 { - return nil, fmt.Errorf("empty key") + return nil, errors.New("empty key") } return groups, nil } diff --git a/vendor/github.com/pelletier/go-toml/lexer.go b/vendor/github.com/pelletier/go-toml/lexer.go index eb4d999..4ba134c 100644 --- a/vendor/github.com/pelletier/go-toml/lexer.go +++ b/vendor/github.com/pelletier/go-toml/lexer.go @@ -129,9 +129,9 @@ func (l *tomlLexer) lexVoid() tomlLexStateFn { next := l.peek() switch next { case '[': - return l.lexKeyGroup + return l.lexTableKey case '#': - return l.lexComment + return l.lexComment(l.lexVoid) case '=': return l.lexEqual case '\r': @@ -182,7 +182,7 @@ func (l *tomlLexer) lexRvalue() tomlLexStateFn { case '}': return l.lexRightCurlyBrace case '#': - return l.lexComment + return l.lexComment(l.lexRvalue) case '"': return l.lexString case '\'': @@ -309,15 +309,17 @@ func (l *tomlLexer) lexKey() tomlLexStateFn { return l.lexVoid } -func (l *tomlLexer) lexComment() tomlLexStateFn { - for next := l.peek(); next != '\n' && next != eof; next = l.peek() { - if next == '\r' && l.follow("\r\n") { - break +func (l *tomlLexer) lexComment(previousState tomlLexStateFn) tomlLexStateFn { + return func() tomlLexStateFn { + for next := l.peek(); next != '\n' && next != eof; next = l.peek() { + if next == '\r' && l.follow("\r\n") { + break + } + l.next() } - l.next() + l.ignore() + return previousState } - l.ignore() - return l.lexVoid } func (l *tomlLexer) lexLeftBracket() tomlLexStateFn { @@ -516,21 +518,21 @@ func (l *tomlLexer) lexString() tomlLexStateFn { return l.lexRvalue } -func (l *tomlLexer) lexKeyGroup() tomlLexStateFn { +func (l *tomlLexer) lexTableKey() tomlLexStateFn { l.next() if l.peek() == '[' { - // token '[[' signifies an array of anonymous key groups + // token '[[' signifies an array of tables l.next() l.emit(tokenDoubleLeftBracket) - return l.lexInsideKeyGroupArray + return l.lexInsideTableArrayKey } - // vanilla key group + // vanilla table key l.emit(tokenLeftBracket) - return l.lexInsideKeyGroup + return l.lexInsideTableKey } -func (l *tomlLexer) lexInsideKeyGroupArray() tomlLexStateFn { +func (l *tomlLexer) lexInsideTableArrayKey() tomlLexStateFn { for r := l.peek(); r != eof; r = l.peek() { switch r { case ']': @@ -545,15 +547,15 @@ func (l *tomlLexer) lexInsideKeyGroupArray() tomlLexStateFn { l.emit(tokenDoubleRightBracket) return l.lexVoid case '[': - return l.errorf("group name cannot contain ']'") + return l.errorf("table array key cannot contain ']'") default: l.next() } } - return l.errorf("unclosed key group array") + return l.errorf("unclosed table array key") } -func (l *tomlLexer) lexInsideKeyGroup() tomlLexStateFn { +func (l *tomlLexer) lexInsideTableKey() tomlLexStateFn { for r := l.peek(); r != eof; r = l.peek() { switch r { case ']': @@ -564,12 +566,12 @@ func (l *tomlLexer) lexInsideKeyGroup() tomlLexStateFn { l.emit(tokenRightBracket) return l.lexVoid case '[': - return l.errorf("group name cannot contain ']'") + return l.errorf("table key cannot contain ']'") default: l.next() } } - return l.errorf("unclosed key group") + return l.errorf("unclosed table key") } func (l *tomlLexer) lexRightBracket() tomlLexStateFn { diff --git a/vendor/github.com/pelletier/go-toml/parser.go b/vendor/github.com/pelletier/go-toml/parser.go index 25932d7..20e90a3 100644 --- a/vendor/github.com/pelletier/go-toml/parser.go +++ b/vendor/github.com/pelletier/go-toml/parser.go @@ -3,6 +3,7 @@ package toml import ( + "errors" "fmt" "reflect" "regexp" @@ -15,8 +16,8 @@ type tomlParser struct { flow chan token tree *TomlTree tokensBuffer []token - currentGroup []string - seenGroupKeys []string + currentTable []string + seenTableKeys []string } type tomlParserStateFn func() tomlParserStateFn @@ -95,13 +96,13 @@ func (p *tomlParser) parseGroupArray() tomlParserStateFn { startToken := p.getToken() // discard the [[ key := p.getToken() if key.typ != tokenKeyGroupArray { - p.raiseError(key, "unexpected token %s, was expecting a key group array", key) + p.raiseError(key, "unexpected token %s, was expecting a table array key", key) } - // get or create group array element at the indicated part in the path + // get or create table array element at the indicated part in the path keys, err := parseKey(key.val) if err != nil { - p.raiseError(key, "invalid group array key: %s", err) + p.raiseError(key, "invalid table array key: %s", err) } p.tree.createSubTree(keys[:len(keys)-1], startToken.Position) // create parent entries destTree := p.tree.GetPath(keys) @@ -111,32 +112,32 @@ func (p *tomlParser) parseGroupArray() tomlParserStateFn { } else if target, ok := destTree.([]*TomlTree); ok && target != nil { array = destTree.([]*TomlTree) } else { - p.raiseError(key, "key %s is already assigned and not of type group array", key) + p.raiseError(key, "key %s is already assigned and not of type table array", key) } - p.currentGroup = keys + p.currentTable = keys - // add a new tree to the end of the group array + // add a new tree to the end of the table array newTree := newTomlTree() newTree.position = startToken.Position array = append(array, newTree) - p.tree.SetPath(p.currentGroup, array) + p.tree.SetPath(p.currentTable, array) - // remove all keys that were children of this group array + // remove all keys that were children of this table array prefix := key.val + "." found := false - for ii := 0; ii < len(p.seenGroupKeys); { - groupKey := p.seenGroupKeys[ii] - if strings.HasPrefix(groupKey, prefix) { - p.seenGroupKeys = append(p.seenGroupKeys[:ii], p.seenGroupKeys[ii+1:]...) + for ii := 0; ii < len(p.seenTableKeys); { + tableKey := p.seenTableKeys[ii] + if strings.HasPrefix(tableKey, prefix) { + p.seenTableKeys = append(p.seenTableKeys[:ii], p.seenTableKeys[ii+1:]...) } else { - found = (groupKey == key.val) + found = (tableKey == key.val) ii++ } } // keep this key name from use by other kinds of assignments if !found { - p.seenGroupKeys = append(p.seenGroupKeys, key.val) + p.seenTableKeys = append(p.seenTableKeys, key.val) } // move to next parser state @@ -148,24 +149,24 @@ func (p *tomlParser) parseGroup() tomlParserStateFn { startToken := p.getToken() // discard the [ key := p.getToken() if key.typ != tokenKeyGroup { - p.raiseError(key, "unexpected token %s, was expecting a key group", key) + p.raiseError(key, "unexpected token %s, was expecting a table key", key) } - for _, item := range p.seenGroupKeys { + for _, item := range p.seenTableKeys { if item == key.val { p.raiseError(key, "duplicated tables") } } - p.seenGroupKeys = append(p.seenGroupKeys, key.val) + p.seenTableKeys = append(p.seenTableKeys, key.val) keys, err := parseKey(key.val) if err != nil { - p.raiseError(key, "invalid group array key: %s", err) + p.raiseError(key, "invalid table array key: %s", err) } if err := p.tree.createSubTree(keys, startToken.Position); err != nil { p.raiseError(key, "%s", err) } p.assume(tokenRightBracket) - p.currentGroup = keys + p.currentTable = keys return p.parseStart } @@ -174,26 +175,26 @@ func (p *tomlParser) parseAssign() tomlParserStateFn { p.assume(tokenEqual) value := p.parseRvalue() - var groupKey []string - if len(p.currentGroup) > 0 { - groupKey = p.currentGroup + var tableKey []string + if len(p.currentTable) > 0 { + tableKey = p.currentTable } else { - groupKey = []string{} + tableKey = []string{} } - // find the group to assign, looking out for arrays of groups + // find the table to assign, looking out for arrays of tables var targetNode *TomlTree - switch node := p.tree.GetPath(groupKey).(type) { + switch node := p.tree.GetPath(tableKey).(type) { case []*TomlTree: targetNode = node[len(node)-1] case *TomlTree: targetNode = node default: - p.raiseError(key, "Unknown group type for path: %s", - strings.Join(groupKey, ".")) + p.raiseError(key, "Unknown table type for path: %s", + strings.Join(tableKey, ".")) } - // assign value to the found group + // assign value to the found table keyVals, err := parseKey(key.val) if err != nil { p.raiseError(key, "%s", err) @@ -203,7 +204,7 @@ func (p *tomlParser) parseAssign() tomlParserStateFn { } keyVal := keyVals[0] localKey := []string{keyVal} - finalKey := append(groupKey, keyVal) + finalKey := append(tableKey, keyVal) if targetNode.GetPath(localKey) != nil { p.raiseError(key, "The following key was defined twice: %s", strings.Join(finalKey, ".")) @@ -211,7 +212,7 @@ func (p *tomlParser) parseAssign() tomlParserStateFn { var toInsert interface{} switch value.(type) { - case *TomlTree: + case *TomlTree, []*TomlTree: toInsert = value default: toInsert = &tomlValue{value, key.Position} @@ -224,7 +225,7 @@ var numberUnderscoreInvalidRegexp *regexp.Regexp func cleanupNumberToken(value string) (string, error) { if numberUnderscoreInvalidRegexp.MatchString(value) { - return "", fmt.Errorf("invalid use of _ in number") + return "", errors.New("invalid use of _ in number") } cleanedVal := strings.Replace(value, "_", "", -1) return cleanedVal, nil @@ -380,8 +381,8 @@ func parseToml(flow chan token) *TomlTree { flow: flow, tree: result, tokensBuffer: make([]token, 0), - currentGroup: make([]string, 0), - seenGroupKeys: make([]string, 0), + currentTable: make([]string, 0), + seenTableKeys: make([]string, 0), } parser.run() return result diff --git a/vendor/github.com/pelletier/go-toml/tomltree_conversions.go b/vendor/github.com/pelletier/go-toml/tomltree_conversions.go index bf9321b..fc8f22b 100644 --- a/vendor/github.com/pelletier/go-toml/tomltree_conversions.go +++ b/vendor/github.com/pelletier/go-toml/tomltree_conversions.go @@ -79,70 +79,96 @@ func toTomlValue(item interface{}, indent int) string { case time.Time: return tab + value.Format(time.RFC3339) case []interface{}: - result := tab + "[\n" + values := []string{} for _, item := range value { - result += toTomlValue(item, indent+2) + ",\n" + values = append(values, toTomlValue(item, 0)) } - return result + tab + "]" + return "[" + strings.Join(values, ",") + "]" case nil: return "" default: - panic(fmt.Sprintf("unsupported value type %T: %v", value, value)) + panic(fmt.Errorf("unsupported value type %T: %v", value, value)) } } // Recursive support function for ToString() -// Outputs a tree, using the provided keyspace to prefix group names +// Outputs a tree, using the provided keyspace to prefix table names func (t *TomlTree) toToml(indent, keyspace string) string { - result := "" + resultChunks := []string{} for k, v := range t.values { // figure out the keyspace combinedKey := k if keyspace != "" { combinedKey = keyspace + "." + combinedKey } + resultChunk := "" // output based on type switch node := v.(type) { case []*TomlTree: for _, item := range node { if len(item.Keys()) > 0 { - result += fmt.Sprintf("\n%s[[%s]]\n", indent, combinedKey) + resultChunk += fmt.Sprintf("\n%s[[%s]]\n", indent, combinedKey) } - result += item.toToml(indent+" ", combinedKey) + resultChunk += item.toToml(indent+" ", combinedKey) } + resultChunks = append(resultChunks, resultChunk) case *TomlTree: if len(node.Keys()) > 0 { - result += fmt.Sprintf("\n%s[%s]\n", indent, combinedKey) + resultChunk += fmt.Sprintf("\n%s[%s]\n", indent, combinedKey) } - result += node.toToml(indent+" ", combinedKey) + resultChunk += node.toToml(indent+" ", combinedKey) + resultChunks = append(resultChunks, resultChunk) case map[string]interface{}: sub := TreeFromMap(node) if len(sub.Keys()) > 0 { - result += fmt.Sprintf("\n%s[%s]\n", indent, combinedKey) + resultChunk += fmt.Sprintf("\n%s[%s]\n", indent, combinedKey) } - result += sub.toToml(indent+" ", combinedKey) + resultChunk += sub.toToml(indent+" ", combinedKey) + resultChunks = append(resultChunks, resultChunk) case map[string]string: sub := TreeFromMap(convertMapStringString(node)) if len(sub.Keys()) > 0 { - result += fmt.Sprintf("\n%s[%s]\n", indent, combinedKey) + resultChunk += fmt.Sprintf("\n%s[%s]\n", indent, combinedKey) } - result += sub.toToml(indent+" ", combinedKey) + resultChunk += sub.toToml(indent+" ", combinedKey) + resultChunks = append(resultChunks, resultChunk) case map[interface{}]interface{}: sub := TreeFromMap(convertMapInterfaceInterface(node)) if len(sub.Keys()) > 0 { - result += fmt.Sprintf("\n%s[%s]\n", indent, combinedKey) + resultChunk += fmt.Sprintf("\n%s[%s]\n", indent, combinedKey) } - result += sub.toToml(indent+" ", combinedKey) + resultChunk += sub.toToml(indent+" ", combinedKey) + resultChunks = append(resultChunks, resultChunk) case *tomlValue: - result += fmt.Sprintf("%s%s = %s\n", indent, k, toTomlValue(node.value, 0)) + resultChunk = fmt.Sprintf("%s%s = %s\n", indent, k, toTomlValue(node.value, 0)) + resultChunks = append([]string{resultChunk}, resultChunks...) default: - result += fmt.Sprintf("%s%s = %s\n", indent, k, toTomlValue(v, 0)) + resultChunk = fmt.Sprintf("%s%s = %s\n", indent, k, toTomlValue(v, 0)) + resultChunks = append([]string{resultChunk}, resultChunks...) } + } - return result + return strings.Join(resultChunks, "") +} + +// Same as ToToml(), but does not panic and returns an error +func (t *TomlTree) toTomlSafe(indent, keyspace string) (result string, err error) { + defer func() { + if r := recover(); r != nil { + result = "" + switch x := r.(type) { + case error: + err = x + default: + err = fmt.Errorf("unknown panic: %s", r) + } + } + }() + result = t.toToml(indent, keyspace) + return } func convertMapStringString(in map[string]string) map[string]interface{} { @@ -161,15 +187,18 @@ func convertMapInterfaceInterface(in map[interface{}]interface{}) map[string]int return result } -// ToString is an alias for String -func (t *TomlTree) ToString() string { - return t.String() +// ToString generates a human-readable representation of the current tree. +// Output spans multiple lines, and is suitable for ingest by a TOML parser. +// If the conversion cannot be performed, ToString returns a non-nil error. +func (t *TomlTree) ToString() (string, error) { + return t.toTomlSafe("", "") } // String generates a human-readable representation of the current tree. -// Output spans multiple lines, and is suitable for ingest by a TOML parser +// Alias of ToString. func (t *TomlTree) String() string { - return t.toToml("", "") + result, _ := t.ToString() + return result } // ToMap recursively generates a representation of the current tree using map[string]interface{}. diff --git a/vendor/github.com/pkg/errors/LICENSE b/vendor/github.com/pkg/errors/LICENSE deleted file mode 100644 index 835ba3e..0000000 --- a/vendor/github.com/pkg/errors/LICENSE +++ /dev/null @@ -1,23 +0,0 @@ -Copyright (c) 2015, Dave Cheney -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - -* Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. - -* Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/pkg/errors/README.md b/vendor/github.com/pkg/errors/README.md deleted file mode 100644 index 273db3c..0000000 --- a/vendor/github.com/pkg/errors/README.md +++ /dev/null @@ -1,52 +0,0 @@ -# errors [![Travis-CI](https://travis-ci.org/pkg/errors.svg)](https://travis-ci.org/pkg/errors) [![AppVeyor](https://ci.appveyor.com/api/projects/status/b98mptawhudj53ep/branch/master?svg=true)](https://ci.appveyor.com/project/davecheney/errors/branch/master) [![GoDoc](https://godoc.org/github.com/pkg/errors?status.svg)](http://godoc.org/github.com/pkg/errors) [![Report card](https://goreportcard.com/badge/github.com/pkg/errors)](https://goreportcard.com/report/github.com/pkg/errors) - -Package errors provides simple error handling primitives. - -`go get github.com/pkg/errors` - -The traditional error handling idiom in Go is roughly akin to -```go -if err != nil { - return err -} -``` -which applied recursively up the call stack results in error reports without context or debugging information. The errors package allows programmers to add context to the failure path in their code in a way that does not destroy the original value of the error. - -## Adding context to an error - -The errors.Wrap function returns a new error that adds context to the original error. For example -```go -_, err := ioutil.ReadAll(r) -if err != nil { - return errors.Wrap(err, "read failed") -} -``` -## Retrieving the cause of an error - -Using `errors.Wrap` constructs a stack of errors, adding context to the preceding error. Depending on the nature of the error it may be necessary to reverse the operation of errors.Wrap to retrieve the original error for inspection. Any error value which implements this interface can be inspected by `errors.Cause`. -```go -type causer interface { - Cause() error -} -``` -`errors.Cause` will recursively retrieve the topmost error which does not implement `causer`, which is assumed to be the original cause. For example: -```go -switch err := errors.Cause(err).(type) { -case *MyError: - // handle specifically -default: - // unknown error -} -``` - -[Read the package documentation for more information](https://godoc.org/github.com/pkg/errors). - -## Contributing - -We welcome pull requests, bug fixes and issue reports. With that said, the bar for adding new symbols to this package is intentionally set high. - -Before proposing a change, please discuss your change by raising an issue. - -## Licence - -BSD-2-Clause diff --git a/vendor/github.com/pkg/errors/appveyor.yml b/vendor/github.com/pkg/errors/appveyor.yml deleted file mode 100644 index a932ead..0000000 --- a/vendor/github.com/pkg/errors/appveyor.yml +++ /dev/null @@ -1,32 +0,0 @@ -version: build-{build}.{branch} - -clone_folder: C:\gopath\src\github.com\pkg\errors -shallow_clone: true # for startup speed - -environment: - GOPATH: C:\gopath - -platform: - - x64 - -# http://www.appveyor.com/docs/installed-software -install: - # some helpful output for debugging builds - - go version - - go env - # pre-installed MinGW at C:\MinGW is 32bit only - # but MSYS2 at C:\msys64 has mingw64 - - set PATH=C:\msys64\mingw64\bin;%PATH% - - gcc --version - - g++ --version - -build_script: - - go install -v ./... - -test_script: - - set PATH=C:\gopath\bin;%PATH% - - go test -v ./... - -#artifacts: -# - path: '%GOPATH%\bin\*.exe' -deploy: off diff --git a/vendor/github.com/pkg/errors/errors.go b/vendor/github.com/pkg/errors/errors.go deleted file mode 100644 index 842ee80..0000000 --- a/vendor/github.com/pkg/errors/errors.go +++ /dev/null @@ -1,269 +0,0 @@ -// Package errors provides simple error handling primitives. -// -// The traditional error handling idiom in Go is roughly akin to -// -// if err != nil { -// return err -// } -// -// which applied recursively up the call stack results in error reports -// without context or debugging information. The errors package allows -// programmers to add context to the failure path in their code in a way -// that does not destroy the original value of the error. -// -// Adding context to an error -// -// The errors.Wrap function returns a new error that adds context to the -// original error by recording a stack trace at the point Wrap is called, -// and the supplied message. For example -// -// _, err := ioutil.ReadAll(r) -// if err != nil { -// return errors.Wrap(err, "read failed") -// } -// -// If additional control is required the errors.WithStack and errors.WithMessage -// functions destructure errors.Wrap into its component operations of annotating -// an error with a stack trace and an a message, respectively. -// -// Retrieving the cause of an error -// -// Using errors.Wrap constructs a stack of errors, adding context to the -// preceding error. Depending on the nature of the error it may be necessary -// to reverse the operation of errors.Wrap to retrieve the original error -// for inspection. Any error value which implements this interface -// -// type causer interface { -// Cause() error -// } -// -// can be inspected by errors.Cause. errors.Cause will recursively retrieve -// the topmost error which does not implement causer, which is assumed to be -// the original cause. For example: -// -// switch err := errors.Cause(err).(type) { -// case *MyError: -// // handle specifically -// default: -// // unknown error -// } -// -// causer interface is not exported by this package, but is considered a part -// of stable public API. -// -// Formatted printing of errors -// -// All error values returned from this package implement fmt.Formatter and can -// be formatted by the fmt package. The following verbs are supported -// -// %s print the error. If the error has a Cause it will be -// printed recursively -// %v see %s -// %+v extended format. Each Frame of the error's StackTrace will -// be printed in detail. -// -// Retrieving the stack trace of an error or wrapper -// -// New, Errorf, Wrap, and Wrapf record a stack trace at the point they are -// invoked. This information can be retrieved with the following interface. -// -// type stackTracer interface { -// StackTrace() errors.StackTrace -// } -// -// Where errors.StackTrace is defined as -// -// type StackTrace []Frame -// -// The Frame type represents a call site in the stack trace. Frame supports -// the fmt.Formatter interface that can be used for printing information about -// the stack trace of this error. For example: -// -// if err, ok := err.(stackTracer); ok { -// for _, f := range err.StackTrace() { -// fmt.Printf("%+s:%d", f) -// } -// } -// -// stackTracer interface is not exported by this package, but is considered a part -// of stable public API. -// -// See the documentation for Frame.Format for more details. -package errors - -import ( - "fmt" - "io" -) - -// New returns an error with the supplied message. -// New also records the stack trace at the point it was called. -func New(message string) error { - return &fundamental{ - msg: message, - stack: callers(), - } -} - -// Errorf formats according to a format specifier and returns the string -// as a value that satisfies error. -// Errorf also records the stack trace at the point it was called. -func Errorf(format string, args ...interface{}) error { - return &fundamental{ - msg: fmt.Sprintf(format, args...), - stack: callers(), - } -} - -// fundamental is an error that has a message and a stack, but no caller. -type fundamental struct { - msg string - *stack -} - -func (f *fundamental) Error() string { return f.msg } - -func (f *fundamental) Format(s fmt.State, verb rune) { - switch verb { - case 'v': - if s.Flag('+') { - io.WriteString(s, f.msg) - f.stack.Format(s, verb) - return - } - fallthrough - case 's': - io.WriteString(s, f.msg) - case 'q': - fmt.Fprintf(s, "%q", f.msg) - } -} - -// WithStack annotates err with a stack trace at the point WithStack was called. -// If err is nil, WithStack returns nil. -func WithStack(err error) error { - if err == nil { - return nil - } - return &withStack{ - err, - callers(), - } -} - -type withStack struct { - error - *stack -} - -func (w *withStack) Cause() error { return w.error } - -func (w *withStack) Format(s fmt.State, verb rune) { - switch verb { - case 'v': - if s.Flag('+') { - fmt.Fprintf(s, "%+v", w.Cause()) - w.stack.Format(s, verb) - return - } - fallthrough - case 's': - io.WriteString(s, w.Error()) - case 'q': - fmt.Fprintf(s, "%q", w.Error()) - } -} - -// Wrap returns an error annotating err with a stack trace -// at the point Wrap is called, and the supplied message. -// If err is nil, Wrap returns nil. -func Wrap(err error, message string) error { - if err == nil { - return nil - } - err = &withMessage{ - cause: err, - msg: message, - } - return &withStack{ - err, - callers(), - } -} - -// Wrapf returns an error annotating err with a stack trace -// at the point Wrapf is call, and the format specifier. -// If err is nil, Wrapf returns nil. -func Wrapf(err error, format string, args ...interface{}) error { - if err == nil { - return nil - } - err = &withMessage{ - cause: err, - msg: fmt.Sprintf(format, args...), - } - return &withStack{ - err, - callers(), - } -} - -// WithMessage annotates err with a new message. -// If err is nil, WithMessage returns nil. -func WithMessage(err error, message string) error { - if err == nil { - return nil - } - return &withMessage{ - cause: err, - msg: message, - } -} - -type withMessage struct { - cause error - msg string -} - -func (w *withMessage) Error() string { return w.msg + ": " + w.cause.Error() } -func (w *withMessage) Cause() error { return w.cause } - -func (w *withMessage) Format(s fmt.State, verb rune) { - switch verb { - case 'v': - if s.Flag('+') { - fmt.Fprintf(s, "%+v\n", w.Cause()) - io.WriteString(s, w.msg) - return - } - fallthrough - case 's', 'q': - io.WriteString(s, w.Error()) - } -} - -// Cause returns the underlying cause of the error, if possible. -// An error value has a cause if it implements the following -// interface: -// -// type causer interface { -// Cause() error -// } -// -// If the error does not implement Cause, the original error will -// be returned. If the error is nil, nil will be returned without further -// investigation. -func Cause(err error) error { - type causer interface { - Cause() error - } - - for err != nil { - cause, ok := err.(causer) - if !ok { - break - } - err = cause.Cause() - } - return err -} diff --git a/vendor/github.com/pkg/errors/stack.go b/vendor/github.com/pkg/errors/stack.go deleted file mode 100644 index 6b1f289..0000000 --- a/vendor/github.com/pkg/errors/stack.go +++ /dev/null @@ -1,178 +0,0 @@ -package errors - -import ( - "fmt" - "io" - "path" - "runtime" - "strings" -) - -// Frame represents a program counter inside a stack frame. -type Frame uintptr - -// pc returns the program counter for this frame; -// multiple frames may have the same PC value. -func (f Frame) pc() uintptr { return uintptr(f) - 1 } - -// file returns the full path to the file that contains the -// function for this Frame's pc. -func (f Frame) file() string { - fn := runtime.FuncForPC(f.pc()) - if fn == nil { - return "unknown" - } - file, _ := fn.FileLine(f.pc()) - return file -} - -// line returns the line number of source code of the -// function for this Frame's pc. -func (f Frame) line() int { - fn := runtime.FuncForPC(f.pc()) - if fn == nil { - return 0 - } - _, line := fn.FileLine(f.pc()) - return line -} - -// Format formats the frame according to the fmt.Formatter interface. -// -// %s source file -// %d source line -// %n function name -// %v equivalent to %s:%d -// -// Format accepts flags that alter the printing of some verbs, as follows: -// -// %+s path of source file relative to the compile time GOPATH -// %+v equivalent to %+s:%d -func (f Frame) Format(s fmt.State, verb rune) { - switch verb { - case 's': - switch { - case s.Flag('+'): - pc := f.pc() - fn := runtime.FuncForPC(pc) - if fn == nil { - io.WriteString(s, "unknown") - } else { - file, _ := fn.FileLine(pc) - fmt.Fprintf(s, "%s\n\t%s", fn.Name(), file) - } - default: - io.WriteString(s, path.Base(f.file())) - } - case 'd': - fmt.Fprintf(s, "%d", f.line()) - case 'n': - name := runtime.FuncForPC(f.pc()).Name() - io.WriteString(s, funcname(name)) - case 'v': - f.Format(s, 's') - io.WriteString(s, ":") - f.Format(s, 'd') - } -} - -// StackTrace is stack of Frames from innermost (newest) to outermost (oldest). -type StackTrace []Frame - -func (st StackTrace) Format(s fmt.State, verb rune) { - switch verb { - case 'v': - switch { - case s.Flag('+'): - for _, f := range st { - fmt.Fprintf(s, "\n%+v", f) - } - case s.Flag('#'): - fmt.Fprintf(s, "%#v", []Frame(st)) - default: - fmt.Fprintf(s, "%v", []Frame(st)) - } - case 's': - fmt.Fprintf(s, "%s", []Frame(st)) - } -} - -// stack represents a stack of program counters. -type stack []uintptr - -func (s *stack) Format(st fmt.State, verb rune) { - switch verb { - case 'v': - switch { - case st.Flag('+'): - for _, pc := range *s { - f := Frame(pc) - fmt.Fprintf(st, "\n%+v", f) - } - } - } -} - -func (s *stack) StackTrace() StackTrace { - f := make([]Frame, len(*s)) - for i := 0; i < len(f); i++ { - f[i] = Frame((*s)[i]) - } - return f -} - -func callers() *stack { - const depth = 32 - var pcs [depth]uintptr - n := runtime.Callers(3, pcs[:]) - var st stack = pcs[0:n] - return &st -} - -// funcname removes the path prefix component of a function's name reported by func.Name(). -func funcname(name string) string { - i := strings.LastIndex(name, "/") - name = name[i+1:] - i = strings.Index(name, ".") - return name[i+1:] -} - -func trimGOPATH(name, file string) string { - // Here we want to get the source file path relative to the compile time - // GOPATH. As of Go 1.6.x there is no direct way to know the compiled - // GOPATH at runtime, but we can infer the number of path segments in the - // GOPATH. We note that fn.Name() returns the function name qualified by - // the import path, which does not include the GOPATH. Thus we can trim - // segments from the beginning of the file path until the number of path - // separators remaining is one more than the number of path separators in - // the function name. For example, given: - // - // GOPATH /home/user - // file /home/user/src/pkg/sub/file.go - // fn.Name() pkg/sub.Type.Method - // - // We want to produce: - // - // pkg/sub/file.go - // - // From this we can easily see that fn.Name() has one less path separator - // than our desired output. We count separators from the end of the file - // path until it finds two more than in the function name and then move - // one character forward to preserve the initial path segment without a - // leading separator. - const sep = "/" - goal := strings.Count(name, sep) + 2 - i := len(file) - for n := 0; n < goal; n++ { - i = strings.LastIndex(file[:i], sep) - if i == -1 { - // not enough separators found, set i so that the slice expression - // below leaves file unmodified - i = -len(sep) - break - } - } - // get back to 0 or trim the leading separator - file = file[i+len(sep):] - return file -} diff --git a/vendor/github.com/pkg/sftp/CONTRIBUTORS b/vendor/github.com/pkg/sftp/CONTRIBUTORS deleted file mode 100644 index 7eff823..0000000 --- a/vendor/github.com/pkg/sftp/CONTRIBUTORS +++ /dev/null @@ -1,2 +0,0 @@ -Dave Cheney -Saulius Gurklys diff --git a/vendor/github.com/pkg/sftp/README.md b/vendor/github.com/pkg/sftp/README.md deleted file mode 100644 index e406b1e..0000000 --- a/vendor/github.com/pkg/sftp/README.md +++ /dev/null @@ -1,27 +0,0 @@ -sftp ----- - -The `sftp` package provides support for file system operations on remote ssh servers using the SFTP subsystem. - -[![UNIX Build Status](https://travis-ci.org/pkg/sftp.svg?branch=master)](https://travis-ci.org/pkg/sftp) [![GoDoc](http://godoc.org/github.com/pkg/sftp?status.svg)](http://godoc.org/github.com/pkg/sftp) - -usage and examples ------------------- - -See [godoc.org/github.com/pkg/sftp](http://godoc.org/github.com/pkg/sftp) for examples and usage. - -The basic operation of the package mirrors the facilities of the [os](http://golang.org/pkg/os) package. - -The Walker interface for directory traversal is heavily inspired by Keith Rarick's [fs](http://godoc.org/github.com/kr/fs) package. - -roadmap -------- - - * There is way too much duplication in the Client methods. If there was an unmarshal(interface{}) method this would reduce a heap of the duplication. - -contributing ------------- - -We welcome pull requests, bug fixes and issue reports. - -Before proposing a large change, first please discuss your change by raising an issue. diff --git a/vendor/github.com/pkg/sftp/attrs.go b/vendor/github.com/pkg/sftp/attrs.go deleted file mode 100644 index 3e4c291..0000000 --- a/vendor/github.com/pkg/sftp/attrs.go +++ /dev/null @@ -1,237 +0,0 @@ -package sftp - -// ssh_FXP_ATTRS support -// see http://tools.ietf.org/html/draft-ietf-secsh-filexfer-02#section-5 - -import ( - "os" - "syscall" - "time" -) - -const ( - ssh_FILEXFER_ATTR_SIZE = 0x00000001 - ssh_FILEXFER_ATTR_UIDGID = 0x00000002 - ssh_FILEXFER_ATTR_PERMISSIONS = 0x00000004 - ssh_FILEXFER_ATTR_ACMODTIME = 0x00000008 - ssh_FILEXFER_ATTR_EXTENDED = 0x80000000 -) - -// fileInfo is an artificial type designed to satisfy os.FileInfo. -type fileInfo struct { - name string - size int64 - mode os.FileMode - mtime time.Time - sys interface{} -} - -// Name returns the base name of the file. -func (fi *fileInfo) Name() string { return fi.name } - -// Size returns the length in bytes for regular files; system-dependent for others. -func (fi *fileInfo) Size() int64 { return fi.size } - -// Mode returns file mode bits. -func (fi *fileInfo) Mode() os.FileMode { return fi.mode } - -// ModTime returns the last modification time of the file. -func (fi *fileInfo) ModTime() time.Time { return fi.mtime } - -// IsDir returns true if the file is a directory. -func (fi *fileInfo) IsDir() bool { return fi.Mode().IsDir() } - -func (fi *fileInfo) Sys() interface{} { return fi.sys } - -// FileStat holds the original unmarshalled values from a call to READDIR or *STAT. -// It is exported for the purposes of accessing the raw values via os.FileInfo.Sys() -type FileStat struct { - Size uint64 - Mode uint32 - Mtime uint32 - Atime uint32 - UID uint32 - GID uint32 - Extended []StatExtended -} - -// StatExtended contains additional, extended information for a FileStat. -type StatExtended struct { - ExtType string - ExtData string -} - -func fileInfoFromStat(st *FileStat, name string) os.FileInfo { - fs := &fileInfo{ - name: name, - size: int64(st.Size), - mode: toFileMode(st.Mode), - mtime: time.Unix(int64(st.Mtime), 0), - sys: st, - } - return fs -} - -func fileStatFromInfo(fi os.FileInfo) (uint32, FileStat) { - mtime := fi.ModTime().Unix() - atime := mtime - var flags uint32 = ssh_FILEXFER_ATTR_SIZE | - ssh_FILEXFER_ATTR_PERMISSIONS | - ssh_FILEXFER_ATTR_ACMODTIME - - fileStat := FileStat{ - Size: uint64(fi.Size()), - Mode: fromFileMode(fi.Mode()), - Mtime: uint32(mtime), - Atime: uint32(atime), - } - - // os specific file stat decoding - fileStatFromInfoOs(fi, &flags, &fileStat) - - return flags, fileStat -} - -func unmarshalAttrs(b []byte) (*FileStat, []byte) { - flags, b := unmarshalUint32(b) - var fs FileStat - if flags&ssh_FILEXFER_ATTR_SIZE == ssh_FILEXFER_ATTR_SIZE { - fs.Size, b = unmarshalUint64(b) - } - if flags&ssh_FILEXFER_ATTR_UIDGID == ssh_FILEXFER_ATTR_UIDGID { - fs.UID, b = unmarshalUint32(b) - } - if flags&ssh_FILEXFER_ATTR_UIDGID == ssh_FILEXFER_ATTR_UIDGID { - fs.GID, b = unmarshalUint32(b) - } - if flags&ssh_FILEXFER_ATTR_PERMISSIONS == ssh_FILEXFER_ATTR_PERMISSIONS { - fs.Mode, b = unmarshalUint32(b) - } - if flags&ssh_FILEXFER_ATTR_ACMODTIME == ssh_FILEXFER_ATTR_ACMODTIME { - fs.Atime, b = unmarshalUint32(b) - fs.Mtime, b = unmarshalUint32(b) - } - if flags&ssh_FILEXFER_ATTR_EXTENDED == ssh_FILEXFER_ATTR_EXTENDED { - var count uint32 - count, b = unmarshalUint32(b) - ext := make([]StatExtended, count, count) - for i := uint32(0); i < count; i++ { - var typ string - var data string - typ, b = unmarshalString(b) - data, b = unmarshalString(b) - ext[i] = StatExtended{typ, data} - } - fs.Extended = ext - } - return &fs, b -} - -func marshalFileInfo(b []byte, fi os.FileInfo) []byte { - // attributes variable struct, and also variable per protocol version - // spec version 3 attributes: - // uint32 flags - // uint64 size present only if flag SSH_FILEXFER_ATTR_SIZE - // uint32 uid present only if flag SSH_FILEXFER_ATTR_UIDGID - // uint32 gid present only if flag SSH_FILEXFER_ATTR_UIDGID - // uint32 permissions present only if flag SSH_FILEXFER_ATTR_PERMISSIONS - // uint32 atime present only if flag SSH_FILEXFER_ACMODTIME - // uint32 mtime present only if flag SSH_FILEXFER_ACMODTIME - // uint32 extended_count present only if flag SSH_FILEXFER_ATTR_EXTENDED - // string extended_type - // string extended_data - // ... more extended data (extended_type - extended_data pairs), - // so that number of pairs equals extended_count - - flags, fileStat := fileStatFromInfo(fi) - - b = marshalUint32(b, flags) - if flags&ssh_FILEXFER_ATTR_SIZE != 0 { - b = marshalUint64(b, fileStat.Size) - } - if flags&ssh_FILEXFER_ATTR_UIDGID != 0 { - b = marshalUint32(b, fileStat.UID) - b = marshalUint32(b, fileStat.GID) - } - if flags&ssh_FILEXFER_ATTR_PERMISSIONS != 0 { - b = marshalUint32(b, fileStat.Mode) - } - if flags&ssh_FILEXFER_ATTR_ACMODTIME != 0 { - b = marshalUint32(b, fileStat.Atime) - b = marshalUint32(b, fileStat.Mtime) - } - - return b -} - -// toFileMode converts sftp filemode bits to the os.FileMode specification -func toFileMode(mode uint32) os.FileMode { - var fm = os.FileMode(mode & 0777) - switch mode & syscall.S_IFMT { - case syscall.S_IFBLK: - fm |= os.ModeDevice - case syscall.S_IFCHR: - fm |= os.ModeDevice | os.ModeCharDevice - case syscall.S_IFDIR: - fm |= os.ModeDir - case syscall.S_IFIFO: - fm |= os.ModeNamedPipe - case syscall.S_IFLNK: - fm |= os.ModeSymlink - case syscall.S_IFREG: - // nothing to do - case syscall.S_IFSOCK: - fm |= os.ModeSocket - } - if mode&syscall.S_ISGID != 0 { - fm |= os.ModeSetgid - } - if mode&syscall.S_ISUID != 0 { - fm |= os.ModeSetuid - } - if mode&syscall.S_ISVTX != 0 { - fm |= os.ModeSticky - } - return fm -} - -// fromFileMode converts from the os.FileMode specification to sftp filemode bits -func fromFileMode(mode os.FileMode) uint32 { - ret := uint32(0) - - if mode&os.ModeDevice != 0 { - if mode&os.ModeCharDevice != 0 { - ret |= syscall.S_IFCHR - } else { - ret |= syscall.S_IFBLK - } - } - if mode&os.ModeDir != 0 { - ret |= syscall.S_IFDIR - } - if mode&os.ModeSymlink != 0 { - ret |= syscall.S_IFLNK - } - if mode&os.ModeNamedPipe != 0 { - ret |= syscall.S_IFIFO - } - if mode&os.ModeSetgid != 0 { - ret |= syscall.S_ISGID - } - if mode&os.ModeSetuid != 0 { - ret |= syscall.S_ISUID - } - if mode&os.ModeSticky != 0 { - ret |= syscall.S_ISVTX - } - if mode&os.ModeSocket != 0 { - ret |= syscall.S_IFSOCK - } - - if mode&os.ModeType == 0 { - ret |= syscall.S_IFREG - } - ret |= uint32(mode & os.ModePerm) - - return ret -} diff --git a/vendor/github.com/pkg/sftp/attrs_stubs.go b/vendor/github.com/pkg/sftp/attrs_stubs.go deleted file mode 100644 index 81cf3ea..0000000 --- a/vendor/github.com/pkg/sftp/attrs_stubs.go +++ /dev/null @@ -1,11 +0,0 @@ -// +build !cgo,!plan9 windows android - -package sftp - -import ( - "os" -) - -func fileStatFromInfoOs(fi os.FileInfo, flags *uint32, fileStat *FileStat) { - // todo -} diff --git a/vendor/github.com/pkg/sftp/attrs_unix.go b/vendor/github.com/pkg/sftp/attrs_unix.go deleted file mode 100644 index ab6ecde..0000000 --- a/vendor/github.com/pkg/sftp/attrs_unix.go +++ /dev/null @@ -1,17 +0,0 @@ -// +build darwin dragonfly freebsd !android,linux netbsd openbsd solaris -// +build cgo - -package sftp - -import ( - "os" - "syscall" -) - -func fileStatFromInfoOs(fi os.FileInfo, flags *uint32, fileStat *FileStat) { - if statt, ok := fi.Sys().(*syscall.Stat_t); ok { - *flags |= ssh_FILEXFER_ATTR_UIDGID - fileStat.UID = statt.Uid - fileStat.GID = statt.Gid - } -} diff --git a/vendor/github.com/pkg/sftp/client.go b/vendor/github.com/pkg/sftp/client.go deleted file mode 100644 index e95bbab..0000000 --- a/vendor/github.com/pkg/sftp/client.go +++ /dev/null @@ -1,1128 +0,0 @@ -package sftp - -import ( - "bytes" - "encoding/binary" - "io" - "os" - "path" - "sync/atomic" - "time" - - "github.com/kr/fs" - "github.com/pkg/errors" - "golang.org/x/crypto/ssh" -) - -// MaxPacket sets the maximum size of the payload. -func MaxPacket(size int) func(*Client) error { - return func(c *Client) error { - if size < 1<<15 { - return errors.Errorf("size must be greater or equal to 32k") - } - c.maxPacket = size - return nil - } -} - -// NewClient creates a new SFTP client on conn, using zero or more option -// functions. -func NewClient(conn *ssh.Client, opts ...func(*Client) error) (*Client, error) { - s, err := conn.NewSession() - if err != nil { - return nil, err - } - if err := s.RequestSubsystem("sftp"); err != nil { - return nil, err - } - pw, err := s.StdinPipe() - if err != nil { - return nil, err - } - pr, err := s.StdoutPipe() - if err != nil { - return nil, err - } - - return NewClientPipe(pr, pw, opts...) -} - -// NewClientPipe creates a new SFTP client given a Reader and a WriteCloser. -// This can be used for connecting to an SFTP server over TCP/TLS or by using -// the system's ssh client program (e.g. via exec.Command). -func NewClientPipe(rd io.Reader, wr io.WriteCloser, opts ...func(*Client) error) (*Client, error) { - sftp := &Client{ - clientConn: clientConn{ - conn: conn{ - Reader: rd, - WriteCloser: wr, - }, - inflight: make(map[uint32]chan<- result), - }, - maxPacket: 1 << 15, - } - if err := sftp.applyOptions(opts...); err != nil { - wr.Close() - return nil, err - } - if err := sftp.sendInit(); err != nil { - wr.Close() - return nil, err - } - if err := sftp.recvVersion(); err != nil { - wr.Close() - return nil, err - } - sftp.clientConn.wg.Add(1) - go sftp.loop() - return sftp, nil -} - -// Client represents an SFTP session on a *ssh.ClientConn SSH connection. -// Multiple Clients can be active on a single SSH connection, and a Client -// may be called concurrently from multiple Goroutines. -// -// Client implements the github.com/kr/fs.FileSystem interface. -type Client struct { - clientConn - - maxPacket int // max packet size read or written. - nextid uint32 -} - -// Create creates the named file mode 0666 (before umask), truncating it if -// it already exists. If successful, methods on the returned File can be -// used for I/O; the associated file descriptor has mode O_RDWR. -func (c *Client) Create(path string) (*File, error) { - return c.open(path, flags(os.O_RDWR|os.O_CREATE|os.O_TRUNC)) -} - -const sftpProtocolVersion = 3 // http://tools.ietf.org/html/draft-ietf-secsh-filexfer-02 - -func (c *Client) sendInit() error { - return c.clientConn.conn.sendPacket(sshFxInitPacket{ - Version: sftpProtocolVersion, // http://tools.ietf.org/html/draft-ietf-secsh-filexfer-02 - }) -} - -// returns the next value of c.nextid -func (c *Client) nextID() uint32 { - return atomic.AddUint32(&c.nextid, 1) -} - -func (c *Client) recvVersion() error { - typ, data, err := c.recvPacket() - if err != nil { - return err - } - if typ != ssh_FXP_VERSION { - return &unexpectedPacketErr{ssh_FXP_VERSION, typ} - } - - version, _ := unmarshalUint32(data) - if version != sftpProtocolVersion { - return &unexpectedVersionErr{sftpProtocolVersion, version} - } - - return nil -} - -// Walk returns a new Walker rooted at root. -func (c *Client) Walk(root string) *fs.Walker { - return fs.WalkFS(root, c) -} - -// ReadDir reads the directory named by dirname and returns a list of -// directory entries. -func (c *Client) ReadDir(p string) ([]os.FileInfo, error) { - handle, err := c.opendir(p) - if err != nil { - return nil, err - } - defer c.close(handle) // this has to defer earlier than the lock below - var attrs []os.FileInfo - var done = false - for !done { - id := c.nextID() - typ, data, err1 := c.sendPacket(sshFxpReaddirPacket{ - ID: id, - Handle: handle, - }) - if err1 != nil { - err = err1 - done = true - break - } - switch typ { - case ssh_FXP_NAME: - sid, data := unmarshalUint32(data) - if sid != id { - return nil, &unexpectedIDErr{id, sid} - } - count, data := unmarshalUint32(data) - for i := uint32(0); i < count; i++ { - var filename string - filename, data = unmarshalString(data) - _, data = unmarshalString(data) // discard longname - var attr *FileStat - attr, data = unmarshalAttrs(data) - if filename == "." || filename == ".." { - continue - } - attrs = append(attrs, fileInfoFromStat(attr, path.Base(filename))) - } - case ssh_FXP_STATUS: - // TODO(dfc) scope warning! - err = normaliseError(unmarshalStatus(id, data)) - done = true - default: - return nil, unimplementedPacketErr(typ) - } - } - if err == io.EOF { - err = nil - } - return attrs, err -} - -func (c *Client) opendir(path string) (string, error) { - id := c.nextID() - typ, data, err := c.sendPacket(sshFxpOpendirPacket{ - ID: id, - Path: path, - }) - if err != nil { - return "", err - } - switch typ { - case ssh_FXP_HANDLE: - sid, data := unmarshalUint32(data) - if sid != id { - return "", &unexpectedIDErr{id, sid} - } - handle, _ := unmarshalString(data) - return handle, nil - case ssh_FXP_STATUS: - return "", unmarshalStatus(id, data) - default: - return "", unimplementedPacketErr(typ) - } -} - -// Stat returns a FileInfo structure describing the file specified by path 'p'. -// If 'p' is a symbolic link, the returned FileInfo structure describes the referent file. -func (c *Client) Stat(p string) (os.FileInfo, error) { - id := c.nextID() - typ, data, err := c.sendPacket(sshFxpStatPacket{ - ID: id, - Path: p, - }) - if err != nil { - return nil, err - } - switch typ { - case ssh_FXP_ATTRS: - sid, data := unmarshalUint32(data) - if sid != id { - return nil, &unexpectedIDErr{id, sid} - } - attr, _ := unmarshalAttrs(data) - return fileInfoFromStat(attr, path.Base(p)), nil - case ssh_FXP_STATUS: - return nil, normaliseError(unmarshalStatus(id, data)) - default: - return nil, unimplementedPacketErr(typ) - } -} - -// Lstat returns a FileInfo structure describing the file specified by path 'p'. -// If 'p' is a symbolic link, the returned FileInfo structure describes the symbolic link. -func (c *Client) Lstat(p string) (os.FileInfo, error) { - id := c.nextID() - typ, data, err := c.sendPacket(sshFxpLstatPacket{ - ID: id, - Path: p, - }) - if err != nil { - return nil, err - } - switch typ { - case ssh_FXP_ATTRS: - sid, data := unmarshalUint32(data) - if sid != id { - return nil, &unexpectedIDErr{id, sid} - } - attr, _ := unmarshalAttrs(data) - return fileInfoFromStat(attr, path.Base(p)), nil - case ssh_FXP_STATUS: - return nil, normaliseError(unmarshalStatus(id, data)) - default: - return nil, unimplementedPacketErr(typ) - } -} - -// ReadLink reads the target of a symbolic link. -func (c *Client) ReadLink(p string) (string, error) { - id := c.nextID() - typ, data, err := c.sendPacket(sshFxpReadlinkPacket{ - ID: id, - Path: p, - }) - if err != nil { - return "", err - } - switch typ { - case ssh_FXP_NAME: - sid, data := unmarshalUint32(data) - if sid != id { - return "", &unexpectedIDErr{id, sid} - } - count, data := unmarshalUint32(data) - if count != 1 { - return "", unexpectedCount(1, count) - } - filename, _ := unmarshalString(data) // ignore dummy attributes - return filename, nil - case ssh_FXP_STATUS: - return "", unmarshalStatus(id, data) - default: - return "", unimplementedPacketErr(typ) - } -} - -// Symlink creates a symbolic link at 'newname', pointing at target 'oldname' -func (c *Client) Symlink(oldname, newname string) error { - id := c.nextID() - typ, data, err := c.sendPacket(sshFxpSymlinkPacket{ - ID: id, - Linkpath: newname, - Targetpath: oldname, - }) - if err != nil { - return err - } - switch typ { - case ssh_FXP_STATUS: - return normaliseError(unmarshalStatus(id, data)) - default: - return unimplementedPacketErr(typ) - } -} - -// setstat is a convience wrapper to allow for changing of various parts of the file descriptor. -func (c *Client) setstat(path string, flags uint32, attrs interface{}) error { - id := c.nextID() - typ, data, err := c.sendPacket(sshFxpSetstatPacket{ - ID: id, - Path: path, - Flags: flags, - Attrs: attrs, - }) - if err != nil { - return err - } - switch typ { - case ssh_FXP_STATUS: - return normaliseError(unmarshalStatus(id, data)) - default: - return unimplementedPacketErr(typ) - } -} - -// Chtimes changes the access and modification times of the named file. -func (c *Client) Chtimes(path string, atime time.Time, mtime time.Time) error { - type times struct { - Atime uint32 - Mtime uint32 - } - attrs := times{uint32(atime.Unix()), uint32(mtime.Unix())} - return c.setstat(path, ssh_FILEXFER_ATTR_ACMODTIME, attrs) -} - -// Chown changes the user and group owners of the named file. -func (c *Client) Chown(path string, uid, gid int) error { - type owner struct { - UID uint32 - GID uint32 - } - attrs := owner{uint32(uid), uint32(gid)} - return c.setstat(path, ssh_FILEXFER_ATTR_UIDGID, attrs) -} - -// Chmod changes the permissions of the named file. -func (c *Client) Chmod(path string, mode os.FileMode) error { - return c.setstat(path, ssh_FILEXFER_ATTR_PERMISSIONS, uint32(mode)) -} - -// Truncate sets the size of the named file. Although it may be safely assumed -// that if the size is less than its current size it will be truncated to fit, -// the SFTP protocol does not specify what behavior the server should do when setting -// size greater than the current size. -func (c *Client) Truncate(path string, size int64) error { - return c.setstat(path, ssh_FILEXFER_ATTR_SIZE, uint64(size)) -} - -// Open opens the named file for reading. If successful, methods on the -// returned file can be used for reading; the associated file descriptor -// has mode O_RDONLY. -func (c *Client) Open(path string) (*File, error) { - return c.open(path, flags(os.O_RDONLY)) -} - -// OpenFile is the generalized open call; most users will use Open or -// Create instead. It opens the named file with specified flag (O_RDONLY -// etc.). If successful, methods on the returned File can be used for I/O. -func (c *Client) OpenFile(path string, f int) (*File, error) { - return c.open(path, flags(f)) -} - -func (c *Client) open(path string, pflags uint32) (*File, error) { - id := c.nextID() - typ, data, err := c.sendPacket(sshFxpOpenPacket{ - ID: id, - Path: path, - Pflags: pflags, - }) - if err != nil { - return nil, err - } - switch typ { - case ssh_FXP_HANDLE: - sid, data := unmarshalUint32(data) - if sid != id { - return nil, &unexpectedIDErr{id, sid} - } - handle, _ := unmarshalString(data) - return &File{c: c, path: path, handle: handle}, nil - case ssh_FXP_STATUS: - return nil, normaliseError(unmarshalStatus(id, data)) - default: - return nil, unimplementedPacketErr(typ) - } -} - -// close closes a handle handle previously returned in the response -// to SSH_FXP_OPEN or SSH_FXP_OPENDIR. The handle becomes invalid -// immediately after this request has been sent. -func (c *Client) close(handle string) error { - id := c.nextID() - typ, data, err := c.sendPacket(sshFxpClosePacket{ - ID: id, - Handle: handle, - }) - if err != nil { - return err - } - switch typ { - case ssh_FXP_STATUS: - return normaliseError(unmarshalStatus(id, data)) - default: - return unimplementedPacketErr(typ) - } -} - -func (c *Client) fstat(handle string) (*FileStat, error) { - id := c.nextID() - typ, data, err := c.sendPacket(sshFxpFstatPacket{ - ID: id, - Handle: handle, - }) - if err != nil { - return nil, err - } - switch typ { - case ssh_FXP_ATTRS: - sid, data := unmarshalUint32(data) - if sid != id { - return nil, &unexpectedIDErr{id, sid} - } - attr, _ := unmarshalAttrs(data) - return attr, nil - case ssh_FXP_STATUS: - return nil, unmarshalStatus(id, data) - default: - return nil, unimplementedPacketErr(typ) - } -} - -// StatVFS retrieves VFS statistics from a remote host. -// -// It implements the statvfs@openssh.com SSH_FXP_EXTENDED feature -// from http://www.opensource.apple.com/source/OpenSSH/OpenSSH-175/openssh/PROTOCOL?txt. -func (c *Client) StatVFS(path string) (*StatVFS, error) { - // send the StatVFS packet to the server - id := c.nextID() - typ, data, err := c.sendPacket(sshFxpStatvfsPacket{ - ID: id, - Path: path, - }) - if err != nil { - return nil, err - } - - switch typ { - // server responded with valid data - case ssh_FXP_EXTENDED_REPLY: - var response StatVFS - err = binary.Read(bytes.NewReader(data), binary.BigEndian, &response) - if err != nil { - return nil, errors.New("can not parse reply") - } - - return &response, nil - - // the resquest failed - case ssh_FXP_STATUS: - return nil, errors.New(fxp(ssh_FXP_STATUS).String()) - - default: - return nil, unimplementedPacketErr(typ) - } -} - -// Join joins any number of path elements into a single path, adding a -// separating slash if necessary. The result is Cleaned; in particular, all -// empty strings are ignored. -func (c *Client) Join(elem ...string) string { return path.Join(elem...) } - -// Remove removes the specified file or directory. An error will be returned if no -// file or directory with the specified path exists, or if the specified directory -// is not empty. -func (c *Client) Remove(path string) error { - err := c.removeFile(path) - if err, ok := err.(*StatusError); ok { - switch err.Code { - // some servers, *cough* osx *cough*, return EPERM, not ENODIR. - // serv-u returns ssh_FX_FILE_IS_A_DIRECTORY - case ssh_FX_PERMISSION_DENIED, ssh_FX_FAILURE, ssh_FX_FILE_IS_A_DIRECTORY: - return c.removeDirectory(path) - } - } - return err -} - -func (c *Client) removeFile(path string) error { - id := c.nextID() - typ, data, err := c.sendPacket(sshFxpRemovePacket{ - ID: id, - Filename: path, - }) - if err != nil { - return err - } - switch typ { - case ssh_FXP_STATUS: - return normaliseError(unmarshalStatus(id, data)) - default: - return unimplementedPacketErr(typ) - } -} - -func (c *Client) removeDirectory(path string) error { - id := c.nextID() - typ, data, err := c.sendPacket(sshFxpRmdirPacket{ - ID: id, - Path: path, - }) - if err != nil { - return err - } - switch typ { - case ssh_FXP_STATUS: - return normaliseError(unmarshalStatus(id, data)) - default: - return unimplementedPacketErr(typ) - } -} - -// Rename renames a file. -func (c *Client) Rename(oldname, newname string) error { - id := c.nextID() - typ, data, err := c.sendPacket(sshFxpRenamePacket{ - ID: id, - Oldpath: oldname, - Newpath: newname, - }) - if err != nil { - return err - } - switch typ { - case ssh_FXP_STATUS: - return normaliseError(unmarshalStatus(id, data)) - default: - return unimplementedPacketErr(typ) - } -} - -func (c *Client) realpath(path string) (string, error) { - id := c.nextID() - typ, data, err := c.sendPacket(sshFxpRealpathPacket{ - ID: id, - Path: path, - }) - if err != nil { - return "", err - } - switch typ { - case ssh_FXP_NAME: - sid, data := unmarshalUint32(data) - if sid != id { - return "", &unexpectedIDErr{id, sid} - } - count, data := unmarshalUint32(data) - if count != 1 { - return "", unexpectedCount(1, count) - } - filename, _ := unmarshalString(data) // ignore attributes - return filename, nil - case ssh_FXP_STATUS: - return "", normaliseError(unmarshalStatus(id, data)) - default: - return "", unimplementedPacketErr(typ) - } -} - -// Getwd returns the current working directory of the server. Operations -// involving relative paths will be based at this location. -func (c *Client) Getwd() (string, error) { - return c.realpath(".") -} - -// Mkdir creates the specified directory. An error will be returned if a file or -// directory with the specified path already exists, or if the directory's -// parent folder does not exist (the method cannot create complete paths). -func (c *Client) Mkdir(path string) error { - id := c.nextID() - typ, data, err := c.sendPacket(sshFxpMkdirPacket{ - ID: id, - Path: path, - }) - if err != nil { - return err - } - switch typ { - case ssh_FXP_STATUS: - return normaliseError(unmarshalStatus(id, data)) - default: - return unimplementedPacketErr(typ) - } -} - -// applyOptions applies options functions to the Client. -// If an error is encountered, option processing ceases. -func (c *Client) applyOptions(opts ...func(*Client) error) error { - for _, f := range opts { - if err := f(c); err != nil { - return err - } - } - return nil -} - -// File represents a remote file. -type File struct { - c *Client - path string - handle string - offset uint64 // current offset within remote file -} - -// Close closes the File, rendering it unusable for I/O. It returns an -// error, if any. -func (f *File) Close() error { - return f.c.close(f.handle) -} - -// Name returns the name of the file as presented to Open or Create. -func (f *File) Name() string { - return f.path -} - -const maxConcurrentRequests = 64 - -// Read reads up to len(b) bytes from the File. It returns the number of -// bytes read and an error, if any. EOF is signaled by a zero count with -// err set to io.EOF. -func (f *File) Read(b []byte) (int, error) { - // Split the read into multiple maxPacket sized concurrent reads - // bounded by maxConcurrentRequests. This allows reads with a suitably - // large buffer to transfer data at a much faster rate due to - // overlapping round trip times. - inFlight := 0 - desiredInFlight := 1 - offset := f.offset - ch := make(chan result, 1) - type inflightRead struct { - b []byte - offset uint64 - } - reqs := map[uint32]inflightRead{} - type offsetErr struct { - offset uint64 - err error - } - var firstErr offsetErr - - sendReq := func(b []byte, offset uint64) { - reqID := f.c.nextID() - f.c.dispatchRequest(ch, sshFxpReadPacket{ - ID: reqID, - Handle: f.handle, - Offset: offset, - Len: uint32(len(b)), - }) - inFlight++ - reqs[reqID] = inflightRead{b: b, offset: offset} - } - - var read int - for len(b) > 0 || inFlight > 0 { - for inFlight < desiredInFlight && len(b) > 0 && firstErr.err == nil { - l := min(len(b), f.c.maxPacket) - rb := b[:l] - sendReq(rb, offset) - offset += uint64(l) - b = b[l:] - } - - if inFlight == 0 { - break - } - select { - case res := <-ch: - inFlight-- - if res.err != nil { - firstErr = offsetErr{offset: 0, err: res.err} - break - } - reqID, data := unmarshalUint32(res.data) - req, ok := reqs[reqID] - if !ok { - firstErr = offsetErr{offset: 0, err: errors.Errorf("sid: %v not found", reqID)} - break - } - delete(reqs, reqID) - switch res.typ { - case ssh_FXP_STATUS: - if firstErr.err == nil || req.offset < firstErr.offset { - firstErr = offsetErr{ - offset: req.offset, - err: normaliseError(unmarshalStatus(reqID, res.data)), - } - break - } - case ssh_FXP_DATA: - l, data := unmarshalUint32(data) - n := copy(req.b, data[:l]) - read += n - if n < len(req.b) { - sendReq(req.b[l:], req.offset+uint64(l)) - } - if desiredInFlight < maxConcurrentRequests { - desiredInFlight++ - } - default: - firstErr = offsetErr{offset: 0, err: unimplementedPacketErr(res.typ)} - break - } - } - } - // If the error is anything other than EOF, then there - // may be gaps in the data copied to the buffer so it's - // best to return 0 so the caller can't make any - // incorrect assumptions about the state of the buffer. - if firstErr.err != nil && firstErr.err != io.EOF { - read = 0 - } - f.offset += uint64(read) - return read, firstErr.err -} - -// WriteTo writes the file to w. The return value is the number of bytes -// written. Any error encountered during the write is also returned. -func (f *File) WriteTo(w io.Writer) (int64, error) { - fi, err := f.Stat() - if err != nil { - return 0, err - } - inFlight := 0 - desiredInFlight := 1 - offset := f.offset - writeOffset := offset - fileSize := uint64(fi.Size()) - ch := make(chan result, 1) - type inflightRead struct { - b []byte - offset uint64 - } - reqs := map[uint32]inflightRead{} - pendingWrites := map[uint64][]byte{} - type offsetErr struct { - offset uint64 - err error - } - var firstErr offsetErr - - sendReq := func(b []byte, offset uint64) { - reqID := f.c.nextID() - f.c.dispatchRequest(ch, sshFxpReadPacket{ - ID: reqID, - Handle: f.handle, - Offset: offset, - Len: uint32(len(b)), - }) - inFlight++ - reqs[reqID] = inflightRead{b: b, offset: offset} - } - - var copied int64 - for firstErr.err == nil || inFlight > 0 { - for inFlight < desiredInFlight && firstErr.err == nil { - b := make([]byte, f.c.maxPacket) - sendReq(b, offset) - offset += uint64(f.c.maxPacket) - if offset > fileSize { - desiredInFlight = 1 - } - } - - if inFlight == 0 { - break - } - select { - case res := <-ch: - inFlight-- - if res.err != nil { - firstErr = offsetErr{offset: 0, err: res.err} - break - } - reqID, data := unmarshalUint32(res.data) - req, ok := reqs[reqID] - if !ok { - firstErr = offsetErr{offset: 0, err: errors.Errorf("sid: %v not found", reqID)} - break - } - delete(reqs, reqID) - switch res.typ { - case ssh_FXP_STATUS: - if firstErr.err == nil || req.offset < firstErr.offset { - firstErr = offsetErr{offset: req.offset, err: normaliseError(unmarshalStatus(reqID, res.data))} - break - } - case ssh_FXP_DATA: - l, data := unmarshalUint32(data) - if req.offset == writeOffset { - nbytes, err := w.Write(data) - copied += int64(nbytes) - if err != nil { - firstErr = offsetErr{offset: req.offset + uint64(nbytes), err: err} - break - } - if nbytes < int(l) { - firstErr = offsetErr{offset: req.offset + uint64(nbytes), err: io.ErrShortWrite} - break - } - switch { - case offset > fileSize: - desiredInFlight = 1 - case desiredInFlight < maxConcurrentRequests: - desiredInFlight++ - } - writeOffset += uint64(nbytes) - for pendingData, ok := pendingWrites[writeOffset]; ok; pendingData, ok = pendingWrites[writeOffset] { - nbytes, err := w.Write(pendingData) - if err != nil { - firstErr = offsetErr{offset: writeOffset + uint64(nbytes), err: err} - break - } - if nbytes < len(pendingData) { - firstErr = offsetErr{offset: writeOffset + uint64(nbytes), err: io.ErrShortWrite} - break - } - writeOffset += uint64(nbytes) - inFlight-- - } - } else { - // Don't write the data yet because - // this response came in out of order - // and we need to wait for responses - // for earlier segments of the file. - inFlight++ // Pending writes should still be considered inFlight. - pendingWrites[req.offset] = data - } - default: - firstErr = offsetErr{offset: 0, err: unimplementedPacketErr(res.typ)} - break - } - } - } - if firstErr.err != io.EOF { - return copied, firstErr.err - } - return copied, nil -} - -// Stat returns the FileInfo structure describing file. If there is an -// error. -func (f *File) Stat() (os.FileInfo, error) { - fs, err := f.c.fstat(f.handle) - if err != nil { - return nil, err - } - return fileInfoFromStat(fs, path.Base(f.path)), nil -} - -// Write writes len(b) bytes to the File. It returns the number of bytes -// written and an error, if any. Write returns a non-nil error when n != -// len(b). -func (f *File) Write(b []byte) (int, error) { - // Split the write into multiple maxPacket sized concurrent writes - // bounded by maxConcurrentRequests. This allows writes with a suitably - // large buffer to transfer data at a much faster rate due to - // overlapping round trip times. - inFlight := 0 - desiredInFlight := 1 - offset := f.offset - ch := make(chan result, 1) - var firstErr error - written := len(b) - for len(b) > 0 || inFlight > 0 { - for inFlight < desiredInFlight && len(b) > 0 && firstErr == nil { - l := min(len(b), f.c.maxPacket) - rb := b[:l] - f.c.dispatchRequest(ch, sshFxpWritePacket{ - ID: f.c.nextID(), - Handle: f.handle, - Offset: offset, - Length: uint32(len(rb)), - Data: rb, - }) - inFlight++ - offset += uint64(l) - b = b[l:] - } - - if inFlight == 0 { - break - } - select { - case res := <-ch: - inFlight-- - if res.err != nil { - firstErr = res.err - break - } - switch res.typ { - case ssh_FXP_STATUS: - id, _ := unmarshalUint32(res.data) - err := normaliseError(unmarshalStatus(id, res.data)) - if err != nil && firstErr == nil { - firstErr = err - break - } - if desiredInFlight < maxConcurrentRequests { - desiredInFlight++ - } - default: - firstErr = unimplementedPacketErr(res.typ) - break - } - } - } - // If error is non-nil, then there may be gaps in the data written to - // the file so it's best to return 0 so the caller can't make any - // incorrect assumptions about the state of the file. - if firstErr != nil { - written = 0 - } - f.offset += uint64(written) - return written, firstErr -} - -// ReadFrom reads data from r until EOF and writes it to the file. The return -// value is the number of bytes read. Any error except io.EOF encountered -// during the read is also returned. -func (f *File) ReadFrom(r io.Reader) (int64, error) { - inFlight := 0 - desiredInFlight := 1 - offset := f.offset - ch := make(chan result, 1) - var firstErr error - read := int64(0) - b := make([]byte, f.c.maxPacket) - for inFlight > 0 || firstErr == nil { - for inFlight < desiredInFlight && firstErr == nil { - n, err := r.Read(b) - if err != nil { - firstErr = err - } - f.c.dispatchRequest(ch, sshFxpWritePacket{ - ID: f.c.nextID(), - Handle: f.handle, - Offset: offset, - Length: uint32(n), - Data: b[:n], - }) - inFlight++ - offset += uint64(n) - read += int64(n) - } - - if inFlight == 0 { - break - } - select { - case res := <-ch: - inFlight-- - if res.err != nil { - firstErr = res.err - break - } - switch res.typ { - case ssh_FXP_STATUS: - id, _ := unmarshalUint32(res.data) - err := normaliseError(unmarshalStatus(id, res.data)) - if err != nil && firstErr == nil { - firstErr = err - break - } - if desiredInFlight < maxConcurrentRequests { - desiredInFlight++ - } - default: - firstErr = unimplementedPacketErr(res.typ) - break - } - } - } - if firstErr == io.EOF { - firstErr = nil - } - // If error is non-nil, then there may be gaps in the data written to - // the file so it's best to return 0 so the caller can't make any - // incorrect assumptions about the state of the file. - if firstErr != nil { - read = 0 - } - f.offset += uint64(read) - return read, firstErr -} - -// Seek implements io.Seeker by setting the client offset for the next Read or -// Write. It returns the next offset read. Seeking before or after the end of -// the file is undefined. Seeking relative to the end calls Stat. -func (f *File) Seek(offset int64, whence int) (int64, error) { - switch whence { - case os.SEEK_SET: - f.offset = uint64(offset) - case os.SEEK_CUR: - f.offset = uint64(int64(f.offset) + offset) - case os.SEEK_END: - fi, err := f.Stat() - if err != nil { - return int64(f.offset), err - } - f.offset = uint64(fi.Size() + offset) - default: - return int64(f.offset), unimplementedSeekWhence(whence) - } - return int64(f.offset), nil -} - -// Chown changes the uid/gid of the current file. -func (f *File) Chown(uid, gid int) error { - return f.c.Chown(f.path, uid, gid) -} - -// Chmod changes the permissions of the current file. -func (f *File) Chmod(mode os.FileMode) error { - return f.c.Chmod(f.path, mode) -} - -// Truncate sets the size of the current file. Although it may be safely assumed -// that if the size is less than its current size it will be truncated to fit, -// the SFTP protocol does not specify what behavior the server should do when setting -// size greater than the current size. -func (f *File) Truncate(size int64) error { - return f.c.Truncate(f.path, size) -} - -func min(a, b int) int { - if a > b { - return b - } - return a -} - -// normaliseError normalises an error into a more standard form that can be -// checked against stdlib errors like io.EOF or os.ErrNotExist. -func normaliseError(err error) error { - switch err := err.(type) { - case *StatusError: - switch err.Code { - case ssh_FX_EOF: - return io.EOF - case ssh_FX_NO_SUCH_FILE: - return os.ErrNotExist - case ssh_FX_OK: - return nil - default: - return err - } - default: - return err - } -} - -func unmarshalStatus(id uint32, data []byte) error { - sid, data := unmarshalUint32(data) - if sid != id { - return &unexpectedIDErr{id, sid} - } - code, data := unmarshalUint32(data) - msg, data, err := unmarshalStringSafe(data) - if err != nil { - return err - } - lang, _, _ := unmarshalStringSafe(data) - return &StatusError{ - Code: code, - msg: msg, - lang: lang, - } -} - -func marshalStatus(b []byte, err StatusError) []byte { - b = marshalUint32(b, err.Code) - b = marshalString(b, err.msg) - b = marshalString(b, err.lang) - return b -} - -// flags converts the flags passed to OpenFile into ssh flags. -// Unsupported flags are ignored. -func flags(f int) uint32 { - var out uint32 - switch f & os.O_WRONLY { - case os.O_WRONLY: - out |= ssh_FXF_WRITE - case os.O_RDONLY: - out |= ssh_FXF_READ - } - if f&os.O_RDWR == os.O_RDWR { - out |= ssh_FXF_READ | ssh_FXF_WRITE - } - if f&os.O_APPEND == os.O_APPEND { - out |= ssh_FXF_APPEND - } - if f&os.O_CREATE == os.O_CREATE { - out |= ssh_FXF_CREAT - } - if f&os.O_TRUNC == os.O_TRUNC { - out |= ssh_FXF_TRUNC - } - if f&os.O_EXCL == os.O_EXCL { - out |= ssh_FXF_EXCL - } - return out -} diff --git a/vendor/github.com/pkg/sftp/conn.go b/vendor/github.com/pkg/sftp/conn.go deleted file mode 100644 index 9b03d11..0000000 --- a/vendor/github.com/pkg/sftp/conn.go +++ /dev/null @@ -1,122 +0,0 @@ -package sftp - -import ( - "encoding" - "io" - "sync" - - "github.com/pkg/errors" -) - -// conn implements a bidirectional channel on which client and server -// connections are multiplexed. -type conn struct { - io.Reader - io.WriteCloser - sync.Mutex // used to serialise writes to sendPacket -} - -func (c *conn) recvPacket() (uint8, []byte, error) { - return recvPacket(c) -} - -func (c *conn) sendPacket(m encoding.BinaryMarshaler) error { - c.Lock() - defer c.Unlock() - return sendPacket(c, m) -} - -type clientConn struct { - conn - wg sync.WaitGroup - sync.Mutex // protects inflight - inflight map[uint32]chan<- result // outstanding requests -} - -// Close closes the SFTP session. -func (c *clientConn) Close() error { - defer c.wg.Wait() - return c.conn.Close() -} - -func (c *clientConn) loop() { - defer c.wg.Done() - err := c.recv() - if err != nil { - c.broadcastErr(err) - } -} - -// recv continuously reads from the server and forwards responses to the -// appropriate channel. -func (c *clientConn) recv() error { - defer c.conn.Close() - for { - typ, data, err := c.recvPacket() - if err != nil { - return err - } - sid, _ := unmarshalUint32(data) - c.Lock() - ch, ok := c.inflight[sid] - delete(c.inflight, sid) - c.Unlock() - if !ok { - // This is an unexpected occurrence. Send the error - // back to all listeners so that they terminate - // gracefully. - return errors.Errorf("sid: %v not fond", sid) - } - ch <- result{typ: typ, data: data} - } -} - -// result captures the result of receiving the a packet from the server -type result struct { - typ byte - data []byte - err error -} - -type idmarshaler interface { - id() uint32 - encoding.BinaryMarshaler -} - -func (c *clientConn) sendPacket(p idmarshaler) (byte, []byte, error) { - ch := make(chan result, 1) - c.dispatchRequest(ch, p) - s := <-ch - return s.typ, s.data, s.err -} - -func (c *clientConn) dispatchRequest(ch chan<- result, p idmarshaler) { - c.Lock() - c.inflight[p.id()] = ch - if err := c.conn.sendPacket(p); err != nil { - delete(c.inflight, p.id()) - ch <- result{err: err} - } - c.Unlock() -} - -// broadcastErr sends an error to all goroutines waiting for a response. -func (c *clientConn) broadcastErr(err error) { - c.Lock() - listeners := make([]chan<- result, 0, len(c.inflight)) - for _, ch := range c.inflight { - listeners = append(listeners, ch) - } - c.Unlock() - for _, ch := range listeners { - ch <- result{err: err} - } -} - -type serverConn struct { - conn -} - -func (s *serverConn) sendError(p id, err error) error { - return s.sendPacket(statusFromError(p, err)) -} diff --git a/vendor/github.com/pkg/sftp/debug.go b/vendor/github.com/pkg/sftp/debug.go deleted file mode 100644 index 3e264ab..0000000 --- a/vendor/github.com/pkg/sftp/debug.go +++ /dev/null @@ -1,9 +0,0 @@ -// +build debug - -package sftp - -import "log" - -func debug(fmt string, args ...interface{}) { - log.Printf(fmt, args...) -} diff --git a/vendor/github.com/pkg/sftp/packet.go b/vendor/github.com/pkg/sftp/packet.go deleted file mode 100644 index fba4159..0000000 --- a/vendor/github.com/pkg/sftp/packet.go +++ /dev/null @@ -1,901 +0,0 @@ -package sftp - -import ( - "bytes" - "encoding" - "encoding/binary" - "fmt" - "io" - "os" - "reflect" - - "github.com/pkg/errors" -) - -var ( - errShortPacket = errors.New("packet too short") - errUnknownExtendedPacket = errors.New("unknown extended packet") -) - -const ( - debugDumpTxPacket = false - debugDumpRxPacket = false - debugDumpTxPacketBytes = false - debugDumpRxPacketBytes = false -) - -func marshalUint32(b []byte, v uint32) []byte { - return append(b, byte(v>>24), byte(v>>16), byte(v>>8), byte(v)) -} - -func marshalUint64(b []byte, v uint64) []byte { - return marshalUint32(marshalUint32(b, uint32(v>>32)), uint32(v)) -} - -func marshalString(b []byte, v string) []byte { - return append(marshalUint32(b, uint32(len(v))), v...) -} - -func marshal(b []byte, v interface{}) []byte { - if v == nil { - return b - } - switch v := v.(type) { - case uint8: - return append(b, v) - case uint32: - return marshalUint32(b, v) - case uint64: - return marshalUint64(b, v) - case string: - return marshalString(b, v) - case os.FileInfo: - return marshalFileInfo(b, v) - default: - switch d := reflect.ValueOf(v); d.Kind() { - case reflect.Struct: - for i, n := 0, d.NumField(); i < n; i++ { - b = append(marshal(b, d.Field(i).Interface())) - } - return b - case reflect.Slice: - for i, n := 0, d.Len(); i < n; i++ { - b = append(marshal(b, d.Index(i).Interface())) - } - return b - default: - panic(fmt.Sprintf("marshal(%#v): cannot handle type %T", v, v)) - } - } -} - -func unmarshalUint32(b []byte) (uint32, []byte) { - v := uint32(b[3]) | uint32(b[2])<<8 | uint32(b[1])<<16 | uint32(b[0])<<24 - return v, b[4:] -} - -func unmarshalUint32Safe(b []byte) (uint32, []byte, error) { - var v uint32 - if len(b) < 4 { - return 0, nil, errShortPacket - } - v, b = unmarshalUint32(b) - return v, b, nil -} - -func unmarshalUint64(b []byte) (uint64, []byte) { - h, b := unmarshalUint32(b) - l, b := unmarshalUint32(b) - return uint64(h)<<32 | uint64(l), b -} - -func unmarshalUint64Safe(b []byte) (uint64, []byte, error) { - var v uint64 - if len(b) < 8 { - return 0, nil, errShortPacket - } - v, b = unmarshalUint64(b) - return v, b, nil -} - -func unmarshalString(b []byte) (string, []byte) { - n, b := unmarshalUint32(b) - return string(b[:n]), b[n:] -} - -func unmarshalStringSafe(b []byte) (string, []byte, error) { - n, b, err := unmarshalUint32Safe(b) - if err != nil { - return "", nil, err - } - if int64(n) > int64(len(b)) { - return "", nil, errShortPacket - } - return string(b[:n]), b[n:], nil -} - -// sendPacket marshals p according to RFC 4234. -func sendPacket(w io.Writer, m encoding.BinaryMarshaler) error { - bb, err := m.MarshalBinary() - if err != nil { - return errors.Errorf("binary marshaller failed: %v", err) - } - if debugDumpTxPacketBytes { - debug("send packet: %s %d bytes %x", fxp(bb[0]), len(bb), bb[1:]) - } else if debugDumpTxPacket { - debug("send packet: %s %d bytes", fxp(bb[0]), len(bb)) - } - l := uint32(len(bb)) - hdr := []byte{byte(l >> 24), byte(l >> 16), byte(l >> 8), byte(l)} - _, err = w.Write(hdr) - if err != nil { - return errors.Errorf("failed to send packet header: %v", err) - } - _, err = w.Write(bb) - if err != nil { - return errors.Errorf("failed to send packet body: %v", err) - } - return nil -} - -func recvPacket(r io.Reader) (uint8, []byte, error) { - var b = []byte{0, 0, 0, 0} - if _, err := io.ReadFull(r, b); err != nil { - return 0, nil, err - } - l, _ := unmarshalUint32(b) - b = make([]byte, l) - if _, err := io.ReadFull(r, b); err != nil { - debug("recv packet %d bytes: err %v", l, err) - return 0, nil, err - } - if debugDumpRxPacketBytes { - debug("recv packet: %s %d bytes %x", fxp(b[0]), l, b[1:]) - } else if debugDumpRxPacket { - debug("recv packet: %s %d bytes", fxp(b[0]), l) - } - return b[0], b[1:], nil -} - -type extensionPair struct { - Name string - Data string -} - -func unmarshalExtensionPair(b []byte) (extensionPair, []byte, error) { - var ep extensionPair - var err error - ep.Name, b, err = unmarshalStringSafe(b) - if err != nil { - return ep, b, err - } - ep.Data, b, err = unmarshalStringSafe(b) - if err != nil { - return ep, b, err - } - return ep, b, err -} - -// Here starts the definition of packets along with their MarshalBinary -// implementations. -// Manually writing the marshalling logic wins us a lot of time and -// allocation. - -type sshFxInitPacket struct { - Version uint32 - Extensions []extensionPair -} - -func (p sshFxInitPacket) MarshalBinary() ([]byte, error) { - l := 1 + 4 // byte + uint32 - for _, e := range p.Extensions { - l += 4 + len(e.Name) + 4 + len(e.Data) - } - - b := make([]byte, 0, l) - b = append(b, ssh_FXP_INIT) - b = marshalUint32(b, p.Version) - for _, e := range p.Extensions { - b = marshalString(b, e.Name) - b = marshalString(b, e.Data) - } - return b, nil -} - -func (p *sshFxInitPacket) UnmarshalBinary(b []byte) error { - var err error - if p.Version, b, err = unmarshalUint32Safe(b); err != nil { - return err - } - for len(b) > 0 { - var ep extensionPair - ep, b, err = unmarshalExtensionPair(b) - if err != nil { - return err - } - p.Extensions = append(p.Extensions, ep) - } - return nil -} - -type sshFxVersionPacket struct { - Version uint32 - Extensions []struct { - Name, Data string - } -} - -func (p sshFxVersionPacket) MarshalBinary() ([]byte, error) { - l := 1 + 4 // byte + uint32 - for _, e := range p.Extensions { - l += 4 + len(e.Name) + 4 + len(e.Data) - } - - b := make([]byte, 0, l) - b = append(b, ssh_FXP_VERSION) - b = marshalUint32(b, p.Version) - for _, e := range p.Extensions { - b = marshalString(b, e.Name) - b = marshalString(b, e.Data) - } - return b, nil -} - -func marshalIDString(packetType byte, id uint32, str string) ([]byte, error) { - l := 1 + 4 + // type(byte) + uint32 - 4 + len(str) - - b := make([]byte, 0, l) - b = append(b, packetType) - b = marshalUint32(b, id) - b = marshalString(b, str) - return b, nil -} - -func unmarshalIDString(b []byte, id *uint32, str *string) error { - var err error - *id, b, err = unmarshalUint32Safe(b) - if err != nil { - return err - } - *str, b, err = unmarshalStringSafe(b) - return err -} - -type sshFxpReaddirPacket struct { - ID uint32 - Handle string -} - -func (p sshFxpReaddirPacket) id() uint32 { return p.ID } - -func (p sshFxpReaddirPacket) MarshalBinary() ([]byte, error) { - return marshalIDString(ssh_FXP_READDIR, p.ID, p.Handle) -} - -func (p *sshFxpReaddirPacket) UnmarshalBinary(b []byte) error { - return unmarshalIDString(b, &p.ID, &p.Handle) -} - -type sshFxpOpendirPacket struct { - ID uint32 - Path string -} - -func (p sshFxpOpendirPacket) id() uint32 { return p.ID } - -func (p sshFxpOpendirPacket) MarshalBinary() ([]byte, error) { - return marshalIDString(ssh_FXP_OPENDIR, p.ID, p.Path) -} - -func (p *sshFxpOpendirPacket) UnmarshalBinary(b []byte) error { - return unmarshalIDString(b, &p.ID, &p.Path) -} - -type sshFxpLstatPacket struct { - ID uint32 - Path string -} - -func (p sshFxpLstatPacket) id() uint32 { return p.ID } - -func (p sshFxpLstatPacket) MarshalBinary() ([]byte, error) { - return marshalIDString(ssh_FXP_LSTAT, p.ID, p.Path) -} - -func (p *sshFxpLstatPacket) UnmarshalBinary(b []byte) error { - return unmarshalIDString(b, &p.ID, &p.Path) -} - -type sshFxpStatPacket struct { - ID uint32 - Path string -} - -func (p sshFxpStatPacket) id() uint32 { return p.ID } - -func (p sshFxpStatPacket) MarshalBinary() ([]byte, error) { - return marshalIDString(ssh_FXP_STAT, p.ID, p.Path) -} - -func (p *sshFxpStatPacket) UnmarshalBinary(b []byte) error { - return unmarshalIDString(b, &p.ID, &p.Path) -} - -type sshFxpFstatPacket struct { - ID uint32 - Handle string -} - -func (p sshFxpFstatPacket) id() uint32 { return p.ID } - -func (p sshFxpFstatPacket) MarshalBinary() ([]byte, error) { - return marshalIDString(ssh_FXP_FSTAT, p.ID, p.Handle) -} - -func (p *sshFxpFstatPacket) UnmarshalBinary(b []byte) error { - return unmarshalIDString(b, &p.ID, &p.Handle) -} - -type sshFxpClosePacket struct { - ID uint32 - Handle string -} - -func (p sshFxpClosePacket) id() uint32 { return p.ID } - -func (p sshFxpClosePacket) MarshalBinary() ([]byte, error) { - return marshalIDString(ssh_FXP_CLOSE, p.ID, p.Handle) -} - -func (p *sshFxpClosePacket) UnmarshalBinary(b []byte) error { - return unmarshalIDString(b, &p.ID, &p.Handle) -} - -type sshFxpRemovePacket struct { - ID uint32 - Filename string -} - -func (p sshFxpRemovePacket) id() uint32 { return p.ID } - -func (p sshFxpRemovePacket) MarshalBinary() ([]byte, error) { - return marshalIDString(ssh_FXP_REMOVE, p.ID, p.Filename) -} - -func (p *sshFxpRemovePacket) UnmarshalBinary(b []byte) error { - return unmarshalIDString(b, &p.ID, &p.Filename) -} - -type sshFxpRmdirPacket struct { - ID uint32 - Path string -} - -func (p sshFxpRmdirPacket) id() uint32 { return p.ID } - -func (p sshFxpRmdirPacket) MarshalBinary() ([]byte, error) { - return marshalIDString(ssh_FXP_RMDIR, p.ID, p.Path) -} - -func (p *sshFxpRmdirPacket) UnmarshalBinary(b []byte) error { - return unmarshalIDString(b, &p.ID, &p.Path) -} - -type sshFxpSymlinkPacket struct { - ID uint32 - Targetpath string - Linkpath string -} - -func (p sshFxpSymlinkPacket) id() uint32 { return p.ID } - -func (p sshFxpSymlinkPacket) MarshalBinary() ([]byte, error) { - l := 1 + 4 + // type(byte) + uint32 - 4 + len(p.Targetpath) + - 4 + len(p.Linkpath) - - b := make([]byte, 0, l) - b = append(b, ssh_FXP_SYMLINK) - b = marshalUint32(b, p.ID) - b = marshalString(b, p.Targetpath) - b = marshalString(b, p.Linkpath) - return b, nil -} - -func (p *sshFxpSymlinkPacket) UnmarshalBinary(b []byte) error { - var err error - if p.ID, b, err = unmarshalUint32Safe(b); err != nil { - return err - } else if p.Targetpath, b, err = unmarshalStringSafe(b); err != nil { - return err - } else if p.Linkpath, b, err = unmarshalStringSafe(b); err != nil { - return err - } - return nil -} - -type sshFxpReadlinkPacket struct { - ID uint32 - Path string -} - -func (p sshFxpReadlinkPacket) id() uint32 { return p.ID } - -func (p sshFxpReadlinkPacket) MarshalBinary() ([]byte, error) { - return marshalIDString(ssh_FXP_READLINK, p.ID, p.Path) -} - -func (p *sshFxpReadlinkPacket) UnmarshalBinary(b []byte) error { - return unmarshalIDString(b, &p.ID, &p.Path) -} - -type sshFxpRealpathPacket struct { - ID uint32 - Path string -} - -func (p sshFxpRealpathPacket) id() uint32 { return p.ID } - -func (p sshFxpRealpathPacket) MarshalBinary() ([]byte, error) { - return marshalIDString(ssh_FXP_REALPATH, p.ID, p.Path) -} - -func (p *sshFxpRealpathPacket) UnmarshalBinary(b []byte) error { - return unmarshalIDString(b, &p.ID, &p.Path) -} - -type sshFxpNameAttr struct { - Name string - LongName string - Attrs []interface{} -} - -func (p sshFxpNameAttr) MarshalBinary() ([]byte, error) { - b := []byte{} - b = marshalString(b, p.Name) - b = marshalString(b, p.LongName) - for _, attr := range p.Attrs { - b = marshal(b, attr) - } - return b, nil -} - -type sshFxpNamePacket struct { - ID uint32 - NameAttrs []sshFxpNameAttr -} - -func (p sshFxpNamePacket) MarshalBinary() ([]byte, error) { - b := []byte{} - b = append(b, ssh_FXP_NAME) - b = marshalUint32(b, p.ID) - b = marshalUint32(b, uint32(len(p.NameAttrs))) - for _, na := range p.NameAttrs { - ab, err := na.MarshalBinary() - if err != nil { - return nil, err - } - - b = append(b, ab...) - } - return b, nil -} - -type sshFxpOpenPacket struct { - ID uint32 - Path string - Pflags uint32 - Flags uint32 // ignored -} - -func (p sshFxpOpenPacket) id() uint32 { return p.ID } - -func (p sshFxpOpenPacket) MarshalBinary() ([]byte, error) { - l := 1 + 4 + - 4 + len(p.Path) + - 4 + 4 - - b := make([]byte, 0, l) - b = append(b, ssh_FXP_OPEN) - b = marshalUint32(b, p.ID) - b = marshalString(b, p.Path) - b = marshalUint32(b, p.Pflags) - b = marshalUint32(b, p.Flags) - return b, nil -} - -func (p *sshFxpOpenPacket) UnmarshalBinary(b []byte) error { - var err error - if p.ID, b, err = unmarshalUint32Safe(b); err != nil { - return err - } else if p.Path, b, err = unmarshalStringSafe(b); err != nil { - return err - } else if p.Pflags, b, err = unmarshalUint32Safe(b); err != nil { - return err - } else if p.Flags, b, err = unmarshalUint32Safe(b); err != nil { - return err - } - return nil -} - -type sshFxpReadPacket struct { - ID uint32 - Handle string - Offset uint64 - Len uint32 -} - -func (p sshFxpReadPacket) id() uint32 { return p.ID } - -func (p sshFxpReadPacket) MarshalBinary() ([]byte, error) { - l := 1 + 4 + // type(byte) + uint32 - 4 + len(p.Handle) + - 8 + 4 // uint64 + uint32 - - b := make([]byte, 0, l) - b = append(b, ssh_FXP_READ) - b = marshalUint32(b, p.ID) - b = marshalString(b, p.Handle) - b = marshalUint64(b, p.Offset) - b = marshalUint32(b, p.Len) - return b, nil -} - -func (p *sshFxpReadPacket) UnmarshalBinary(b []byte) error { - var err error - if p.ID, b, err = unmarshalUint32Safe(b); err != nil { - return err - } else if p.Handle, b, err = unmarshalStringSafe(b); err != nil { - return err - } else if p.Offset, b, err = unmarshalUint64Safe(b); err != nil { - return err - } else if p.Len, b, err = unmarshalUint32Safe(b); err != nil { - return err - } - return nil -} - -type sshFxpRenamePacket struct { - ID uint32 - Oldpath string - Newpath string -} - -func (p sshFxpRenamePacket) id() uint32 { return p.ID } - -func (p sshFxpRenamePacket) MarshalBinary() ([]byte, error) { - l := 1 + 4 + // type(byte) + uint32 - 4 + len(p.Oldpath) + - 4 + len(p.Newpath) - - b := make([]byte, 0, l) - b = append(b, ssh_FXP_RENAME) - b = marshalUint32(b, p.ID) - b = marshalString(b, p.Oldpath) - b = marshalString(b, p.Newpath) - return b, nil -} - -func (p *sshFxpRenamePacket) UnmarshalBinary(b []byte) error { - var err error - if p.ID, b, err = unmarshalUint32Safe(b); err != nil { - return err - } else if p.Oldpath, b, err = unmarshalStringSafe(b); err != nil { - return err - } else if p.Newpath, b, err = unmarshalStringSafe(b); err != nil { - return err - } - return nil -} - -type sshFxpWritePacket struct { - ID uint32 - Handle string - Offset uint64 - Length uint32 - Data []byte -} - -func (p sshFxpWritePacket) id() uint32 { return p.ID } - -func (p sshFxpWritePacket) MarshalBinary() ([]byte, error) { - l := 1 + 4 + // type(byte) + uint32 - 4 + len(p.Handle) + - 8 + 4 + // uint64 + uint32 - len(p.Data) - - b := make([]byte, 0, l) - b = append(b, ssh_FXP_WRITE) - b = marshalUint32(b, p.ID) - b = marshalString(b, p.Handle) - b = marshalUint64(b, p.Offset) - b = marshalUint32(b, p.Length) - b = append(b, p.Data...) - return b, nil -} - -func (p *sshFxpWritePacket) UnmarshalBinary(b []byte) error { - var err error - if p.ID, b, err = unmarshalUint32Safe(b); err != nil { - return err - } else if p.Handle, b, err = unmarshalStringSafe(b); err != nil { - return err - } else if p.Offset, b, err = unmarshalUint64Safe(b); err != nil { - return err - } else if p.Length, b, err = unmarshalUint32Safe(b); err != nil { - return err - } else if uint32(len(b)) < p.Length { - return errShortPacket - } - - p.Data = append([]byte{}, b[:p.Length]...) - return nil -} - -type sshFxpMkdirPacket struct { - ID uint32 - Path string - Flags uint32 // ignored -} - -func (p sshFxpMkdirPacket) id() uint32 { return p.ID } - -func (p sshFxpMkdirPacket) MarshalBinary() ([]byte, error) { - l := 1 + 4 + // type(byte) + uint32 - 4 + len(p.Path) + - 4 // uint32 - - b := make([]byte, 0, l) - b = append(b, ssh_FXP_MKDIR) - b = marshalUint32(b, p.ID) - b = marshalString(b, p.Path) - b = marshalUint32(b, p.Flags) - return b, nil -} - -func (p *sshFxpMkdirPacket) UnmarshalBinary(b []byte) error { - var err error - if p.ID, b, err = unmarshalUint32Safe(b); err != nil { - return err - } else if p.Path, b, err = unmarshalStringSafe(b); err != nil { - return err - } else if p.Flags, b, err = unmarshalUint32Safe(b); err != nil { - return err - } - return nil -} - -type sshFxpSetstatPacket struct { - ID uint32 - Path string - Flags uint32 - Attrs interface{} -} - -type sshFxpFsetstatPacket struct { - ID uint32 - Handle string - Flags uint32 - Attrs interface{} -} - -func (p sshFxpSetstatPacket) id() uint32 { return p.ID } -func (p sshFxpFsetstatPacket) id() uint32 { return p.ID } - -func (p sshFxpSetstatPacket) MarshalBinary() ([]byte, error) { - l := 1 + 4 + // type(byte) + uint32 - 4 + len(p.Path) + - 4 // uint32 + uint64 - - b := make([]byte, 0, l) - b = append(b, ssh_FXP_SETSTAT) - b = marshalUint32(b, p.ID) - b = marshalString(b, p.Path) - b = marshalUint32(b, p.Flags) - b = marshal(b, p.Attrs) - return b, nil -} - -func (p sshFxpFsetstatPacket) MarshalBinary() ([]byte, error) { - l := 1 + 4 + // type(byte) + uint32 - 4 + len(p.Handle) + - 4 // uint32 + uint64 - - b := make([]byte, 0, l) - b = append(b, ssh_FXP_FSETSTAT) - b = marshalUint32(b, p.ID) - b = marshalString(b, p.Handle) - b = marshalUint32(b, p.Flags) - b = marshal(b, p.Attrs) - return b, nil -} - -func (p *sshFxpSetstatPacket) UnmarshalBinary(b []byte) error { - var err error - if p.ID, b, err = unmarshalUint32Safe(b); err != nil { - return err - } else if p.Path, b, err = unmarshalStringSafe(b); err != nil { - return err - } else if p.Flags, b, err = unmarshalUint32Safe(b); err != nil { - return err - } - p.Attrs = b - return nil -} - -func (p *sshFxpFsetstatPacket) UnmarshalBinary(b []byte) error { - var err error - if p.ID, b, err = unmarshalUint32Safe(b); err != nil { - return err - } else if p.Handle, b, err = unmarshalStringSafe(b); err != nil { - return err - } else if p.Flags, b, err = unmarshalUint32Safe(b); err != nil { - return err - } - p.Attrs = b - return nil -} - -type sshFxpHandlePacket struct { - ID uint32 - Handle string -} - -func (p sshFxpHandlePacket) MarshalBinary() ([]byte, error) { - b := []byte{ssh_FXP_HANDLE} - b = marshalUint32(b, p.ID) - b = marshalString(b, p.Handle) - return b, nil -} - -type sshFxpStatusPacket struct { - ID uint32 - StatusError -} - -func (p sshFxpStatusPacket) MarshalBinary() ([]byte, error) { - b := []byte{ssh_FXP_STATUS} - b = marshalUint32(b, p.ID) - b = marshalStatus(b, p.StatusError) - return b, nil -} - -type sshFxpDataPacket struct { - ID uint32 - Length uint32 - Data []byte -} - -func (p sshFxpDataPacket) MarshalBinary() ([]byte, error) { - b := []byte{ssh_FXP_DATA} - b = marshalUint32(b, p.ID) - b = marshalUint32(b, p.Length) - b = append(b, p.Data[:p.Length]...) - return b, nil -} - -func (p *sshFxpDataPacket) UnmarshalBinary(b []byte) error { - var err error - if p.ID, b, err = unmarshalUint32Safe(b); err != nil { - return err - } else if p.Length, b, err = unmarshalUint32Safe(b); err != nil { - return err - } else if uint32(len(b)) < p.Length { - return errors.New("truncated packet") - } - - p.Data = make([]byte, p.Length) - copy(p.Data, b) - return nil -} - -type sshFxpStatvfsPacket struct { - ID uint32 - Path string -} - -func (p sshFxpStatvfsPacket) id() uint32 { return p.ID } - -func (p sshFxpStatvfsPacket) MarshalBinary() ([]byte, error) { - l := 1 + 4 + // type(byte) + uint32 - len(p.Path) + - len("statvfs@openssh.com") - - b := make([]byte, 0, l) - b = append(b, ssh_FXP_EXTENDED) - b = marshalUint32(b, p.ID) - b = marshalString(b, "statvfs@openssh.com") - b = marshalString(b, p.Path) - return b, nil -} - -// A StatVFS contains statistics about a filesystem. -type StatVFS struct { - ID uint32 - Bsize uint64 /* file system block size */ - Frsize uint64 /* fundamental fs block size */ - Blocks uint64 /* number of blocks (unit f_frsize) */ - Bfree uint64 /* free blocks in file system */ - Bavail uint64 /* free blocks for non-root */ - Files uint64 /* total file inodes */ - Ffree uint64 /* free file inodes */ - Favail uint64 /* free file inodes for to non-root */ - Fsid uint64 /* file system id */ - Flag uint64 /* bit mask of f_flag values */ - Namemax uint64 /* maximum filename length */ -} - -// TotalSpace calculates the amount of total space in a filesystem. -func (p *StatVFS) TotalSpace() uint64 { - return p.Frsize * p.Blocks -} - -// FreeSpace calculates the amount of free space in a filesystem. -func (p *StatVFS) FreeSpace() uint64 { - return p.Frsize * p.Bfree -} - -// Convert to ssh_FXP_EXTENDED_REPLY packet binary format -func (p *StatVFS) MarshalBinary() ([]byte, error) { - var buf bytes.Buffer - buf.Write([]byte{ssh_FXP_EXTENDED_REPLY}) - err := binary.Write(&buf, binary.BigEndian, p) - return buf.Bytes(), err -} - -type sshFxpExtendedPacket struct { - ID uint32 - ExtendedRequest string - SpecificPacket interface { - serverRespondablePacket - readonly() bool - } -} - -func (p sshFxpExtendedPacket) id() uint32 { return p.ID } -func (p sshFxpExtendedPacket) readonly() bool { return p.SpecificPacket.readonly() } - -func (p sshFxpExtendedPacket) respond(svr *Server) error { - return p.SpecificPacket.respond(svr) -} - -func (p *sshFxpExtendedPacket) UnmarshalBinary(b []byte) error { - var err error - bOrig := b - if p.ID, b, err = unmarshalUint32Safe(b); err != nil { - return err - } else if p.ExtendedRequest, b, err = unmarshalStringSafe(b); err != nil { - return err - } - - // specific unmarshalling - switch p.ExtendedRequest { - case "statvfs@openssh.com": - p.SpecificPacket = &sshFxpExtendedPacketStatVFS{} - default: - return errUnknownExtendedPacket - } - - return p.SpecificPacket.UnmarshalBinary(bOrig) -} - -type sshFxpExtendedPacketStatVFS struct { - ID uint32 - ExtendedRequest string - Path string -} - -func (p sshFxpExtendedPacketStatVFS) id() uint32 { return p.ID } -func (p sshFxpExtendedPacketStatVFS) readonly() bool { return true } -func (p *sshFxpExtendedPacketStatVFS) UnmarshalBinary(b []byte) error { - var err error - if p.ID, b, err = unmarshalUint32Safe(b); err != nil { - return err - } else if p.ExtendedRequest, b, err = unmarshalStringSafe(b); err != nil { - return err - } else if p.Path, b, err = unmarshalStringSafe(b); err != nil { - return err - } - return nil -} diff --git a/vendor/github.com/pkg/sftp/release.go b/vendor/github.com/pkg/sftp/release.go deleted file mode 100644 index b695528..0000000 --- a/vendor/github.com/pkg/sftp/release.go +++ /dev/null @@ -1,5 +0,0 @@ -// +build !debug - -package sftp - -func debug(fmt string, args ...interface{}) {} diff --git a/vendor/github.com/pkg/sftp/server.go b/vendor/github.com/pkg/sftp/server.go deleted file mode 100644 index e097bda..0000000 --- a/vendor/github.com/pkg/sftp/server.go +++ /dev/null @@ -1,607 +0,0 @@ -package sftp - -// sftp server counterpart - -import ( - "encoding" - "fmt" - "io" - "io/ioutil" - "os" - "path/filepath" - "strconv" - "sync" - "syscall" - "time" - - "github.com/pkg/errors" -) - -const ( - sftpServerWorkerCount = 8 -) - -// Server is an SSH File Transfer Protocol (sftp) server. -// This is intended to provide the sftp subsystem to an ssh server daemon. -// This implementation currently supports most of sftp server protocol version 3, -// as specified at http://tools.ietf.org/html/draft-ietf-secsh-filexfer-02 -type Server struct { - serverConn - debugStream io.Writer - readOnly bool - pktChan chan rxPacket - openFiles map[string]*os.File - openFilesLock sync.RWMutex - handleCount int - maxTxPacket uint32 -} - -func (svr *Server) nextHandle(f *os.File) string { - svr.openFilesLock.Lock() - defer svr.openFilesLock.Unlock() - svr.handleCount++ - handle := strconv.Itoa(svr.handleCount) - svr.openFiles[handle] = f - return handle -} - -func (svr *Server) closeHandle(handle string) error { - svr.openFilesLock.Lock() - defer svr.openFilesLock.Unlock() - if f, ok := svr.openFiles[handle]; ok { - delete(svr.openFiles, handle) - return f.Close() - } - - return syscall.EBADF -} - -func (svr *Server) getHandle(handle string) (*os.File, bool) { - svr.openFilesLock.RLock() - defer svr.openFilesLock.RUnlock() - f, ok := svr.openFiles[handle] - return f, ok -} - -type serverRespondablePacket interface { - encoding.BinaryUnmarshaler - id() uint32 - respond(svr *Server) error -} - -// NewServer creates a new Server instance around the provided streams, serving -// content from the root of the filesystem. Optionally, ServerOption -// functions may be specified to further configure the Server. -// -// A subsequent call to Serve() is required to begin serving files over SFTP. -func NewServer(rwc io.ReadWriteCloser, options ...ServerOption) (*Server, error) { - s := &Server{ - serverConn: serverConn{ - conn: conn{ - Reader: rwc, - WriteCloser: rwc, - }, - }, - debugStream: ioutil.Discard, - pktChan: make(chan rxPacket, sftpServerWorkerCount), - openFiles: make(map[string]*os.File), - maxTxPacket: 1 << 15, - } - - for _, o := range options { - if err := o(s); err != nil { - return nil, err - } - } - - return s, nil -} - -// A ServerOption is a function which applies configuration to a Server. -type ServerOption func(*Server) error - -// WithDebug enables Server debugging output to the supplied io.Writer. -func WithDebug(w io.Writer) ServerOption { - return func(s *Server) error { - s.debugStream = w - return nil - } -} - -// ReadOnly configures a Server to serve files in read-only mode. -func ReadOnly() ServerOption { - return func(s *Server) error { - s.readOnly = true - return nil - } -} - -type rxPacket struct { - pktType fxp - pktBytes []byte -} - -// Up to N parallel servers -func (svr *Server) sftpServerWorker() error { - for p := range svr.pktChan { - var pkt interface { - encoding.BinaryUnmarshaler - id() uint32 - } - var readonly = true - switch p.pktType { - case ssh_FXP_INIT: - pkt = &sshFxInitPacket{} - case ssh_FXP_LSTAT: - pkt = &sshFxpLstatPacket{} - case ssh_FXP_OPEN: - pkt = &sshFxpOpenPacket{} - // readonly handled specially below - case ssh_FXP_CLOSE: - pkt = &sshFxpClosePacket{} - case ssh_FXP_READ: - pkt = &sshFxpReadPacket{} - case ssh_FXP_WRITE: - pkt = &sshFxpWritePacket{} - readonly = false - case ssh_FXP_FSTAT: - pkt = &sshFxpFstatPacket{} - case ssh_FXP_SETSTAT: - pkt = &sshFxpSetstatPacket{} - readonly = false - case ssh_FXP_FSETSTAT: - pkt = &sshFxpFsetstatPacket{} - readonly = false - case ssh_FXP_OPENDIR: - pkt = &sshFxpOpendirPacket{} - case ssh_FXP_READDIR: - pkt = &sshFxpReaddirPacket{} - case ssh_FXP_REMOVE: - pkt = &sshFxpRemovePacket{} - readonly = false - case ssh_FXP_MKDIR: - pkt = &sshFxpMkdirPacket{} - readonly = false - case ssh_FXP_RMDIR: - pkt = &sshFxpRmdirPacket{} - readonly = false - case ssh_FXP_REALPATH: - pkt = &sshFxpRealpathPacket{} - case ssh_FXP_STAT: - pkt = &sshFxpStatPacket{} - case ssh_FXP_RENAME: - pkt = &sshFxpRenamePacket{} - readonly = false - case ssh_FXP_READLINK: - pkt = &sshFxpReadlinkPacket{} - case ssh_FXP_SYMLINK: - pkt = &sshFxpSymlinkPacket{} - readonly = false - case ssh_FXP_EXTENDED: - pkt = &sshFxpExtendedPacket{} - default: - return errors.Errorf("unhandled packet type: %s", p.pktType) - } - if err := pkt.UnmarshalBinary(p.pktBytes); err != nil { - return err - } - - // handle FXP_OPENDIR specially - switch pkt := pkt.(type) { - case *sshFxpOpenPacket: - readonly = pkt.readonly() - case *sshFxpExtendedPacket: - readonly = pkt.SpecificPacket.readonly() - } - - // If server is operating read-only and a write operation is requested, - // return permission denied - if !readonly && svr.readOnly { - if err := svr.sendError(pkt, syscall.EPERM); err != nil { - return errors.Wrap(err, "failed to send read only packet response") - } - continue - } - - if err := handlePacket(svr, pkt); err != nil { - return err - } - } - return nil -} - -func handlePacket(s *Server, p interface{}) error { - switch p := p.(type) { - case *sshFxInitPacket: - return s.sendPacket(sshFxVersionPacket{sftpProtocolVersion, nil}) - case *sshFxpStatPacket: - // stat the requested file - info, err := os.Stat(p.Path) - if err != nil { - return s.sendError(p, err) - } - return s.sendPacket(sshFxpStatResponse{ - ID: p.ID, - info: info, - }) - case *sshFxpLstatPacket: - // stat the requested file - info, err := os.Lstat(p.Path) - if err != nil { - return s.sendError(p, err) - } - return s.sendPacket(sshFxpStatResponse{ - ID: p.ID, - info: info, - }) - case *sshFxpFstatPacket: - f, ok := s.getHandle(p.Handle) - if !ok { - return s.sendError(p, syscall.EBADF) - } - - info, err := f.Stat() - if err != nil { - return s.sendError(p, err) - } - - return s.sendPacket(sshFxpStatResponse{ - ID: p.ID, - info: info, - }) - case *sshFxpMkdirPacket: - // TODO FIXME: ignore flags field - err := os.Mkdir(p.Path, 0755) - return s.sendError(p, err) - case *sshFxpRmdirPacket: - err := os.Remove(p.Path) - return s.sendError(p, err) - case *sshFxpRemovePacket: - err := os.Remove(p.Filename) - return s.sendError(p, err) - case *sshFxpRenamePacket: - err := os.Rename(p.Oldpath, p.Newpath) - return s.sendError(p, err) - case *sshFxpSymlinkPacket: - err := os.Symlink(p.Targetpath, p.Linkpath) - return s.sendError(p, err) - case *sshFxpClosePacket: - return s.sendError(p, s.closeHandle(p.Handle)) - case *sshFxpReadlinkPacket: - f, err := os.Readlink(p.Path) - if err != nil { - return s.sendError(p, err) - } - - return s.sendPacket(sshFxpNamePacket{ - ID: p.ID, - NameAttrs: []sshFxpNameAttr{{ - Name: f, - LongName: f, - Attrs: emptyFileStat, - }}, - }) - - case *sshFxpRealpathPacket: - f, err := filepath.Abs(p.Path) - if err != nil { - return s.sendError(p, err) - } - f = filepath.Clean(f) - return s.sendPacket(sshFxpNamePacket{ - ID: p.ID, - NameAttrs: []sshFxpNameAttr{{ - Name: f, - LongName: f, - Attrs: emptyFileStat, - }}, - }) - case *sshFxpOpendirPacket: - return sshFxpOpenPacket{ - ID: p.ID, - Path: p.Path, - Pflags: ssh_FXF_READ, - }.respond(s) - case *sshFxpReadPacket: - f, ok := s.getHandle(p.Handle) - if !ok { - return s.sendError(p, syscall.EBADF) - } - - data := make([]byte, clamp(p.Len, s.maxTxPacket)) - n, err := f.ReadAt(data, int64(p.Offset)) - if err != nil && (err != io.EOF || n == 0) { - return s.sendError(p, err) - } - return s.sendPacket(sshFxpDataPacket{ - ID: p.ID, - Length: uint32(n), - Data: data[:n], - }) - case *sshFxpWritePacket: - f, ok := s.getHandle(p.Handle) - if !ok { - return s.sendError(p, syscall.EBADF) - } - - _, err := f.WriteAt(p.Data, int64(p.Offset)) - return s.sendError(p, err) - case serverRespondablePacket: - err := p.respond(s) - return errors.Wrap(err, "pkt.respond failed") - default: - return errors.Errorf("unexpected packet type %T", p) - } -} - -// Serve serves SFTP connections until the streams stop or the SFTP subsystem -// is stopped. -func (svr *Server) Serve() error { - var wg sync.WaitGroup - wg.Add(sftpServerWorkerCount) - for i := 0; i < sftpServerWorkerCount; i++ { - go func() { - defer wg.Done() - if err := svr.sftpServerWorker(); err != nil { - svr.conn.Close() // shuts down recvPacket - } - }() - } - - var err error - var pktType uint8 - var pktBytes []byte - for { - pktType, pktBytes, err = svr.recvPacket() - if err != nil { - break - } - svr.pktChan <- rxPacket{fxp(pktType), pktBytes} - } - - close(svr.pktChan) // shuts down sftpServerWorkers - wg.Wait() // wait for all workers to exit - - // close any still-open files - for handle, file := range svr.openFiles { - fmt.Fprintf(svr.debugStream, "sftp server file with handle %q left open: %v\n", handle, file.Name()) - file.Close() - } - return err // error from recvPacket -} - -type id interface { - id() uint32 -} - -// The init packet has no ID, so we just return a zero-value ID -func (p sshFxInitPacket) id() uint32 { return 0 } - -type sshFxpStatResponse struct { - ID uint32 - info os.FileInfo -} - -func (p sshFxpStatResponse) MarshalBinary() ([]byte, error) { - b := []byte{ssh_FXP_ATTRS} - b = marshalUint32(b, p.ID) - b = marshalFileInfo(b, p.info) - return b, nil -} - -var emptyFileStat = []interface{}{uint32(0)} - -func (p sshFxpOpenPacket) readonly() bool { - return !p.hasPflags(ssh_FXF_WRITE) -} - -func (p sshFxpOpenPacket) hasPflags(flags ...uint32) bool { - for _, f := range flags { - if p.Pflags&f == 0 { - return false - } - } - return true -} - -func (p sshFxpOpenPacket) respond(svr *Server) error { - var osFlags int - if p.hasPflags(ssh_FXF_READ, ssh_FXF_WRITE) { - osFlags |= os.O_RDWR - } else if p.hasPflags(ssh_FXF_WRITE) { - osFlags |= os.O_WRONLY - } else if p.hasPflags(ssh_FXF_READ) { - osFlags |= os.O_RDONLY - } else { - // how are they opening? - return svr.sendError(p, syscall.EINVAL) - } - - if p.hasPflags(ssh_FXF_APPEND) { - osFlags |= os.O_APPEND - } - if p.hasPflags(ssh_FXF_CREAT) { - osFlags |= os.O_CREATE - } - if p.hasPflags(ssh_FXF_TRUNC) { - osFlags |= os.O_TRUNC - } - if p.hasPflags(ssh_FXF_EXCL) { - osFlags |= os.O_EXCL - } - - f, err := os.OpenFile(p.Path, osFlags, 0644) - if err != nil { - return svr.sendError(p, err) - } - - handle := svr.nextHandle(f) - return svr.sendPacket(sshFxpHandlePacket{p.ID, handle}) -} - -func (p sshFxpReaddirPacket) respond(svr *Server) error { - f, ok := svr.getHandle(p.Handle) - if !ok { - return svr.sendError(p, syscall.EBADF) - } - - dirname := f.Name() - dirents, err := f.Readdir(128) - if err != nil { - return svr.sendError(p, err) - } - - ret := sshFxpNamePacket{ID: p.ID} - for _, dirent := range dirents { - ret.NameAttrs = append(ret.NameAttrs, sshFxpNameAttr{ - Name: dirent.Name(), - LongName: runLs(dirname, dirent), - Attrs: []interface{}{dirent}, - }) - } - return svr.sendPacket(ret) -} - -func (p sshFxpSetstatPacket) respond(svr *Server) error { - // additional unmarshalling is required for each possibility here - b := p.Attrs.([]byte) - var err error - - debug("setstat name \"%s\"", p.Path) - if (p.Flags & ssh_FILEXFER_ATTR_SIZE) != 0 { - var size uint64 - if size, b, err = unmarshalUint64Safe(b); err == nil { - err = os.Truncate(p.Path, int64(size)) - } - } - if (p.Flags & ssh_FILEXFER_ATTR_PERMISSIONS) != 0 { - var mode uint32 - if mode, b, err = unmarshalUint32Safe(b); err == nil { - err = os.Chmod(p.Path, os.FileMode(mode)) - } - } - if (p.Flags & ssh_FILEXFER_ATTR_ACMODTIME) != 0 { - var atime uint32 - var mtime uint32 - if atime, b, err = unmarshalUint32Safe(b); err != nil { - } else if mtime, b, err = unmarshalUint32Safe(b); err != nil { - } else { - atimeT := time.Unix(int64(atime), 0) - mtimeT := time.Unix(int64(mtime), 0) - err = os.Chtimes(p.Path, atimeT, mtimeT) - } - } - if (p.Flags & ssh_FILEXFER_ATTR_UIDGID) != 0 { - var uid uint32 - var gid uint32 - if uid, b, err = unmarshalUint32Safe(b); err != nil { - } else if gid, b, err = unmarshalUint32Safe(b); err != nil { - } else { - err = os.Chown(p.Path, int(uid), int(gid)) - } - } - - return svr.sendError(p, err) -} - -func (p sshFxpFsetstatPacket) respond(svr *Server) error { - f, ok := svr.getHandle(p.Handle) - if !ok { - return svr.sendError(p, syscall.EBADF) - } - - // additional unmarshalling is required for each possibility here - b := p.Attrs.([]byte) - var err error - - debug("fsetstat name \"%s\"", f.Name()) - if (p.Flags & ssh_FILEXFER_ATTR_SIZE) != 0 { - var size uint64 - if size, b, err = unmarshalUint64Safe(b); err == nil { - err = f.Truncate(int64(size)) - } - } - if (p.Flags & ssh_FILEXFER_ATTR_PERMISSIONS) != 0 { - var mode uint32 - if mode, b, err = unmarshalUint32Safe(b); err == nil { - err = f.Chmod(os.FileMode(mode)) - } - } - if (p.Flags & ssh_FILEXFER_ATTR_ACMODTIME) != 0 { - var atime uint32 - var mtime uint32 - if atime, b, err = unmarshalUint32Safe(b); err != nil { - } else if mtime, b, err = unmarshalUint32Safe(b); err != nil { - } else { - atimeT := time.Unix(int64(atime), 0) - mtimeT := time.Unix(int64(mtime), 0) - err = os.Chtimes(f.Name(), atimeT, mtimeT) - } - } - if (p.Flags & ssh_FILEXFER_ATTR_UIDGID) != 0 { - var uid uint32 - var gid uint32 - if uid, b, err = unmarshalUint32Safe(b); err != nil { - } else if gid, b, err = unmarshalUint32Safe(b); err != nil { - } else { - err = f.Chown(int(uid), int(gid)) - } - } - - return svr.sendError(p, err) -} - -// translateErrno translates a syscall error number to a SFTP error code. -func translateErrno(errno syscall.Errno) uint32 { - switch errno { - case 0: - return ssh_FX_OK - case syscall.ENOENT: - return ssh_FX_NO_SUCH_FILE - case syscall.EPERM: - return ssh_FX_PERMISSION_DENIED - } - - return ssh_FX_FAILURE -} - -func statusFromError(p id, err error) sshFxpStatusPacket { - ret := sshFxpStatusPacket{ - ID: p.id(), - StatusError: StatusError{ - // ssh_FX_OK = 0 - // ssh_FX_EOF = 1 - // ssh_FX_NO_SUCH_FILE = 2 ENOENT - // ssh_FX_PERMISSION_DENIED = 3 - // ssh_FX_FAILURE = 4 - // ssh_FX_BAD_MESSAGE = 5 - // ssh_FX_NO_CONNECTION = 6 - // ssh_FX_CONNECTION_LOST = 7 - // ssh_FX_OP_UNSUPPORTED = 8 - Code: ssh_FX_OK, - }, - } - if err != nil { - debug("statusFromError: error is %T %#v", err, err) - ret.StatusError.Code = ssh_FX_FAILURE - ret.StatusError.msg = err.Error() - if err == io.EOF { - ret.StatusError.Code = ssh_FX_EOF - } else if errno, ok := err.(syscall.Errno); ok { - ret.StatusError.Code = translateErrno(errno) - } else if pathError, ok := err.(*os.PathError); ok { - debug("statusFromError: error is %T %#v", pathError.Err, pathError.Err) - if errno, ok := pathError.Err.(syscall.Errno); ok { - ret.StatusError.Code = translateErrno(errno) - } - } - } - return ret -} - -func clamp(v, max uint32) uint32 { - if v > max { - return max - } - return v -} diff --git a/vendor/github.com/pkg/sftp/server_statvfs_darwin.go b/vendor/github.com/pkg/sftp/server_statvfs_darwin.go deleted file mode 100644 index 8c01dac..0000000 --- a/vendor/github.com/pkg/sftp/server_statvfs_darwin.go +++ /dev/null @@ -1,21 +0,0 @@ -package sftp - -import ( - "syscall" -) - -func statvfsFromStatfst(stat *syscall.Statfs_t) (*StatVFS, error) { - return &StatVFS{ - Bsize: uint64(stat.Bsize), - Frsize: uint64(stat.Bsize), // fragment size is a linux thing; use block size here - Blocks: stat.Blocks, - Bfree: stat.Bfree, - Bavail: stat.Bavail, - Files: stat.Files, - Ffree: stat.Ffree, - Favail: stat.Ffree, // not sure how to calculate Favail - Fsid: uint64(uint64(stat.Fsid.Val[1])<<32 | uint64(stat.Fsid.Val[0])), // endianness? - Flag: uint64(stat.Flags), // assuming POSIX? - Namemax: 1024, // man 2 statfs shows: #define MAXPATHLEN 1024 - }, nil -} diff --git a/vendor/github.com/pkg/sftp/server_statvfs_impl.go b/vendor/github.com/pkg/sftp/server_statvfs_impl.go deleted file mode 100644 index c26870e..0000000 --- a/vendor/github.com/pkg/sftp/server_statvfs_impl.go +++ /dev/null @@ -1,25 +0,0 @@ -// +build darwin linux,!gccgo - -// fill in statvfs structure with OS specific values -// Statfs_t is different per-kernel, and only exists on some unixes (not Solaris for instance) - -package sftp - -import ( - "syscall" -) - -func (p sshFxpExtendedPacketStatVFS) respond(svr *Server) error { - stat := &syscall.Statfs_t{} - if err := syscall.Statfs(p.Path, stat); err != nil { - return svr.sendPacket(statusFromError(p, err)) - } - - retPkt, err := statvfsFromStatfst(stat) - if err != nil { - return svr.sendPacket(statusFromError(p, err)) - } - retPkt.ID = p.ID - - return svr.sendPacket(retPkt) -} diff --git a/vendor/github.com/pkg/sftp/server_statvfs_linux.go b/vendor/github.com/pkg/sftp/server_statvfs_linux.go deleted file mode 100644 index 43478e8..0000000 --- a/vendor/github.com/pkg/sftp/server_statvfs_linux.go +++ /dev/null @@ -1,22 +0,0 @@ -// +build !gccgo,linux - -package sftp - -import ( - "syscall" -) - -func statvfsFromStatfst(stat *syscall.Statfs_t) (*StatVFS, error) { - return &StatVFS{ - Bsize: uint64(stat.Bsize), - Frsize: uint64(stat.Frsize), - Blocks: stat.Blocks, - Bfree: stat.Bfree, - Bavail: stat.Bavail, - Files: stat.Files, - Ffree: stat.Ffree, - Favail: stat.Ffree, // not sure how to calculate Favail - Flag: uint64(stat.Flags), // assuming POSIX? - Namemax: uint64(stat.Namelen), - }, nil -} diff --git a/vendor/github.com/pkg/sftp/server_statvfs_stubs.go b/vendor/github.com/pkg/sftp/server_statvfs_stubs.go deleted file mode 100644 index 1512a13..0000000 --- a/vendor/github.com/pkg/sftp/server_statvfs_stubs.go +++ /dev/null @@ -1,11 +0,0 @@ -// +build !darwin,!linux gccgo - -package sftp - -import ( - "syscall" -) - -func (p sshFxpExtendedPacketStatVFS) respond(svr *Server) error { - return syscall.ENOTSUP -} diff --git a/vendor/github.com/pkg/sftp/server_stubs.go b/vendor/github.com/pkg/sftp/server_stubs.go deleted file mode 100644 index 3b1ddbd..0000000 --- a/vendor/github.com/pkg/sftp/server_stubs.go +++ /dev/null @@ -1,12 +0,0 @@ -// +build !cgo,!plan9 windows android - -package sftp - -import ( - "os" - "path" -) - -func runLs(dirname string, dirent os.FileInfo) string { - return path.Join(dirname, dirent.Name()) -} diff --git a/vendor/github.com/pkg/sftp/server_unix.go b/vendor/github.com/pkg/sftp/server_unix.go deleted file mode 100644 index 8c3f0b4..0000000 --- a/vendor/github.com/pkg/sftp/server_unix.go +++ /dev/null @@ -1,143 +0,0 @@ -// +build darwin dragonfly freebsd !android,linux netbsd openbsd solaris -// +build cgo - -package sftp - -import ( - "fmt" - "os" - "path" - "syscall" - "time" -) - -func runLsTypeWord(dirent os.FileInfo) string { - // find first character, the type char - // b Block special file. - // c Character special file. - // d Directory. - // l Symbolic link. - // s Socket link. - // p FIFO. - // - Regular file. - tc := '-' - mode := dirent.Mode() - if (mode & os.ModeDir) != 0 { - tc = 'd' - } else if (mode & os.ModeDevice) != 0 { - tc = 'b' - if (mode & os.ModeCharDevice) != 0 { - tc = 'c' - } - } else if (mode & os.ModeSymlink) != 0 { - tc = 'l' - } else if (mode & os.ModeSocket) != 0 { - tc = 's' - } else if (mode & os.ModeNamedPipe) != 0 { - tc = 'p' - } - - // owner - orc := '-' - if (mode & 0400) != 0 { - orc = 'r' - } - owc := '-' - if (mode & 0200) != 0 { - owc = 'w' - } - oxc := '-' - ox := (mode & 0100) != 0 - setuid := (mode & os.ModeSetuid) != 0 - if ox && setuid { - oxc = 's' - } else if setuid { - oxc = 'S' - } else if ox { - oxc = 'x' - } - - // group - grc := '-' - if (mode & 040) != 0 { - grc = 'r' - } - gwc := '-' - if (mode & 020) != 0 { - gwc = 'w' - } - gxc := '-' - gx := (mode & 010) != 0 - setgid := (mode & os.ModeSetgid) != 0 - if gx && setgid { - gxc = 's' - } else if setgid { - gxc = 'S' - } else if gx { - gxc = 'x' - } - - // all / others - arc := '-' - if (mode & 04) != 0 { - arc = 'r' - } - awc := '-' - if (mode & 02) != 0 { - awc = 'w' - } - axc := '-' - ax := (mode & 01) != 0 - sticky := (mode & os.ModeSticky) != 0 - if ax && sticky { - axc = 't' - } else if sticky { - axc = 'T' - } else if ax { - axc = 'x' - } - - return fmt.Sprintf("%c%c%c%c%c%c%c%c%c%c", tc, orc, owc, oxc, grc, gwc, gxc, arc, awc, axc) -} - -func runLsStatt(dirname string, dirent os.FileInfo, statt *syscall.Stat_t) string { - // example from openssh sftp server: - // crw-rw-rw- 1 root wheel 0 Jul 31 20:52 ttyvd - // format: - // {directory / char device / etc}{rwxrwxrwx} {number of links} owner group size month day [time (this year) | year (otherwise)] name - - typeword := runLsTypeWord(dirent) - numLinks := statt.Nlink - uid := statt.Uid - gid := statt.Gid - username := fmt.Sprintf("%d", uid) - groupname := fmt.Sprintf("%d", gid) - // TODO FIXME: uid -> username, gid -> groupname lookup for ls -l format output - - mtime := dirent.ModTime() - monthStr := mtime.Month().String()[0:3] - day := mtime.Day() - year := mtime.Year() - now := time.Now() - isOld := mtime.Before(now.Add(-time.Hour * 24 * 365 / 2)) - - yearOrTime := fmt.Sprintf("%02d:%02d", mtime.Hour(), mtime.Minute()) - if isOld { - yearOrTime = fmt.Sprintf("%d", year) - } - - return fmt.Sprintf("%s %4d %-8s %-8s %8d %s %2d %5s %s", typeword, numLinks, username, groupname, dirent.Size(), monthStr, day, yearOrTime, dirent.Name()) -} - -// ls -l style output for a file, which is in the 'long output' section of a readdir response packet -// this is a very simple (lazy) implementation, just enough to look almost like openssh in a few basic cases -func runLs(dirname string, dirent os.FileInfo) string { - dsys := dirent.Sys() - if dsys == nil { - } else if statt, ok := dsys.(*syscall.Stat_t); !ok { - } else { - return runLsStatt(dirname, dirent, statt) - } - - return path.Join(dirname, dirent.Name()) -} diff --git a/vendor/github.com/pkg/sftp/sftp.go b/vendor/github.com/pkg/sftp/sftp.go deleted file mode 100644 index 22184af..0000000 --- a/vendor/github.com/pkg/sftp/sftp.go +++ /dev/null @@ -1,217 +0,0 @@ -// Package sftp implements the SSH File Transfer Protocol as described in -// https://filezilla-project.org/specs/draft-ietf-secsh-filexfer-02.txt -package sftp - -import ( - "fmt" - - "github.com/pkg/errors" -) - -const ( - ssh_FXP_INIT = 1 - ssh_FXP_VERSION = 2 - ssh_FXP_OPEN = 3 - ssh_FXP_CLOSE = 4 - ssh_FXP_READ = 5 - ssh_FXP_WRITE = 6 - ssh_FXP_LSTAT = 7 - ssh_FXP_FSTAT = 8 - ssh_FXP_SETSTAT = 9 - ssh_FXP_FSETSTAT = 10 - ssh_FXP_OPENDIR = 11 - ssh_FXP_READDIR = 12 - ssh_FXP_REMOVE = 13 - ssh_FXP_MKDIR = 14 - ssh_FXP_RMDIR = 15 - ssh_FXP_REALPATH = 16 - ssh_FXP_STAT = 17 - ssh_FXP_RENAME = 18 - ssh_FXP_READLINK = 19 - ssh_FXP_SYMLINK = 20 - ssh_FXP_STATUS = 101 - ssh_FXP_HANDLE = 102 - ssh_FXP_DATA = 103 - ssh_FXP_NAME = 104 - ssh_FXP_ATTRS = 105 - ssh_FXP_EXTENDED = 200 - ssh_FXP_EXTENDED_REPLY = 201 -) - -const ( - ssh_FX_OK = 0 - ssh_FX_EOF = 1 - ssh_FX_NO_SUCH_FILE = 2 - ssh_FX_PERMISSION_DENIED = 3 - ssh_FX_FAILURE = 4 - ssh_FX_BAD_MESSAGE = 5 - ssh_FX_NO_CONNECTION = 6 - ssh_FX_CONNECTION_LOST = 7 - ssh_FX_OP_UNSUPPORTED = 8 - - // see draft-ietf-secsh-filexfer-13 - // https://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-9.1 - ssh_FX_INVALID_HANDLE = 9 - ssh_FX_NO_SUCH_PATH = 10 - ssh_FX_FILE_ALREADY_EXISTS = 11 - ssh_FX_WRITE_PROTECT = 12 - ssh_FX_NO_MEDIA = 13 - ssh_FX_NO_SPACE_ON_FILESYSTEM = 14 - ssh_FX_QUOTA_EXCEEDED = 15 - ssh_FX_UNKNOWN_PRINCIPAL = 16 - ssh_FX_LOCK_CONFLICT = 17 - ssh_FX_DIR_NOT_EMPTY = 18 - ssh_FX_NOT_A_DIRECTORY = 19 - ssh_FX_INVALID_FILENAME = 20 - ssh_FX_LINK_LOOP = 21 - ssh_FX_CANNOT_DELETE = 22 - ssh_FX_INVALID_PARAMETER = 23 - ssh_FX_FILE_IS_A_DIRECTORY = 24 - ssh_FX_BYTE_RANGE_LOCK_CONFLICT = 25 - ssh_FX_BYTE_RANGE_LOCK_REFUSED = 26 - ssh_FX_DELETE_PENDING = 27 - ssh_FX_FILE_CORRUPT = 28 - ssh_FX_OWNER_INVALID = 29 - ssh_FX_GROUP_INVALID = 30 - ssh_FX_NO_MATCHING_BYTE_RANGE_LOCK = 31 -) - -const ( - ssh_FXF_READ = 0x00000001 - ssh_FXF_WRITE = 0x00000002 - ssh_FXF_APPEND = 0x00000004 - ssh_FXF_CREAT = 0x00000008 - ssh_FXF_TRUNC = 0x00000010 - ssh_FXF_EXCL = 0x00000020 -) - -type fxp uint8 - -func (f fxp) String() string { - switch f { - case ssh_FXP_INIT: - return "SSH_FXP_INIT" - case ssh_FXP_VERSION: - return "SSH_FXP_VERSION" - case ssh_FXP_OPEN: - return "SSH_FXP_OPEN" - case ssh_FXP_CLOSE: - return "SSH_FXP_CLOSE" - case ssh_FXP_READ: - return "SSH_FXP_READ" - case ssh_FXP_WRITE: - return "SSH_FXP_WRITE" - case ssh_FXP_LSTAT: - return "SSH_FXP_LSTAT" - case ssh_FXP_FSTAT: - return "SSH_FXP_FSTAT" - case ssh_FXP_SETSTAT: - return "SSH_FXP_SETSTAT" - case ssh_FXP_FSETSTAT: - return "SSH_FXP_FSETSTAT" - case ssh_FXP_OPENDIR: - return "SSH_FXP_OPENDIR" - case ssh_FXP_READDIR: - return "SSH_FXP_READDIR" - case ssh_FXP_REMOVE: - return "SSH_FXP_REMOVE" - case ssh_FXP_MKDIR: - return "SSH_FXP_MKDIR" - case ssh_FXP_RMDIR: - return "SSH_FXP_RMDIR" - case ssh_FXP_REALPATH: - return "SSH_FXP_REALPATH" - case ssh_FXP_STAT: - return "SSH_FXP_STAT" - case ssh_FXP_RENAME: - return "SSH_FXP_RENAME" - case ssh_FXP_READLINK: - return "SSH_FXP_READLINK" - case ssh_FXP_SYMLINK: - return "SSH_FXP_SYMLINK" - case ssh_FXP_STATUS: - return "SSH_FXP_STATUS" - case ssh_FXP_HANDLE: - return "SSH_FXP_HANDLE" - case ssh_FXP_DATA: - return "SSH_FXP_DATA" - case ssh_FXP_NAME: - return "SSH_FXP_NAME" - case ssh_FXP_ATTRS: - return "SSH_FXP_ATTRS" - case ssh_FXP_EXTENDED: - return "SSH_FXP_EXTENDED" - case ssh_FXP_EXTENDED_REPLY: - return "SSH_FXP_EXTENDED_REPLY" - default: - return "unknown" - } -} - -type fx uint8 - -func (f fx) String() string { - switch f { - case ssh_FX_OK: - return "SSH_FX_OK" - case ssh_FX_EOF: - return "SSH_FX_EOF" - case ssh_FX_NO_SUCH_FILE: - return "SSH_FX_NO_SUCH_FILE" - case ssh_FX_PERMISSION_DENIED: - return "SSH_FX_PERMISSION_DENIED" - case ssh_FX_FAILURE: - return "SSH_FX_FAILURE" - case ssh_FX_BAD_MESSAGE: - return "SSH_FX_BAD_MESSAGE" - case ssh_FX_NO_CONNECTION: - return "SSH_FX_NO_CONNECTION" - case ssh_FX_CONNECTION_LOST: - return "SSH_FX_CONNECTION_LOST" - case ssh_FX_OP_UNSUPPORTED: - return "SSH_FX_OP_UNSUPPORTED" - default: - return "unknown" - } -} - -type unexpectedPacketErr struct { - want, got uint8 -} - -func (u *unexpectedPacketErr) Error() string { - return fmt.Sprintf("sftp: unexpected packet: want %v, got %v", fxp(u.want), fxp(u.got)) -} - -func unimplementedPacketErr(u uint8) error { - return errors.Errorf("sftp: unimplemented packet type: got %v", fxp(u)) -} - -type unexpectedIDErr struct{ want, got uint32 } - -func (u *unexpectedIDErr) Error() string { - return fmt.Sprintf("sftp: unexpected id: want %v, got %v", u.want, u.got) -} - -func unimplementedSeekWhence(whence int) error { - return errors.Errorf("sftp: unimplemented seek whence %v", whence) -} - -func unexpectedCount(want, got uint32) error { - return errors.Errorf("sftp: unexpected count: want %v, got %v", want, got) -} - -type unexpectedVersionErr struct{ want, got uint32 } - -func (u *unexpectedVersionErr) Error() string { - return fmt.Sprintf("sftp: unexpected server version: want %v, got %v", u.want, u.got) -} - -// A StatusError is returned when an SFTP operation fails, and provides -// additional information about the failure. -type StatusError struct { - Code uint32 - msg, lang string -} - -func (s *StatusError) Error() string { return fmt.Sprintf("sftp: %q (%v)", s.msg, fx(s.Code)) } diff --git a/vendor/github.com/pmezard/go-difflib/LICENSE b/vendor/github.com/pmezard/go-difflib/LICENSE deleted file mode 100644 index c67dad6..0000000 --- a/vendor/github.com/pmezard/go-difflib/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -Copyright (c) 2013, Patrick Mezard -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright -notice, this list of conditions and the following disclaimer in the -documentation and/or other materials provided with the distribution. - The names of its contributors may not be used to endorse or promote -products derived from this software without specific prior written -permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS -IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED -TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A -PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED -TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/pmezard/go-difflib/difflib/difflib.go b/vendor/github.com/pmezard/go-difflib/difflib/difflib.go deleted file mode 100644 index 64cc40f..0000000 --- a/vendor/github.com/pmezard/go-difflib/difflib/difflib.go +++ /dev/null @@ -1,758 +0,0 @@ -// Package difflib is a partial port of Python difflib module. -// -// It provides tools to compare sequences of strings and generate textual diffs. -// -// The following class and functions have been ported: -// -// - SequenceMatcher -// -// - unified_diff -// -// - context_diff -// -// Getting unified diffs was the main goal of the port. Keep in mind this code -// is mostly suitable to output text differences in a human friendly way, there -// are no guarantees generated diffs are consumable by patch(1). -package difflib - -import ( - "bufio" - "bytes" - "fmt" - "io" - "strings" -) - -func min(a, b int) int { - if a < b { - return a - } - return b -} - -func max(a, b int) int { - if a > b { - return a - } - return b -} - -func calculateRatio(matches, length int) float64 { - if length > 0 { - return 2.0 * float64(matches) / float64(length) - } - return 1.0 -} - -type Match struct { - A int - B int - Size int -} - -type OpCode struct { - Tag byte - I1 int - I2 int - J1 int - J2 int -} - -// SequenceMatcher compares sequence of strings. The basic -// algorithm predates, and is a little fancier than, an algorithm -// published in the late 1980's by Ratcliff and Obershelp under the -// hyperbolic name "gestalt pattern matching". The basic idea is to find -// the longest contiguous matching subsequence that contains no "junk" -// elements (R-O doesn't address junk). The same idea is then applied -// recursively to the pieces of the sequences to the left and to the right -// of the matching subsequence. This does not yield minimal edit -// sequences, but does tend to yield matches that "look right" to people. -// -// SequenceMatcher tries to compute a "human-friendly diff" between two -// sequences. Unlike e.g. UNIX(tm) diff, the fundamental notion is the -// longest *contiguous* & junk-free matching subsequence. That's what -// catches peoples' eyes. The Windows(tm) windiff has another interesting -// notion, pairing up elements that appear uniquely in each sequence. -// That, and the method here, appear to yield more intuitive difference -// reports than does diff. This method appears to be the least vulnerable -// to synching up on blocks of "junk lines", though (like blank lines in -// ordinary text files, or maybe "

    " lines in HTML files). That may be -// because this is the only method of the 3 that has a *concept* of -// "junk" . -// -// Timing: Basic R-O is cubic time worst case and quadratic time expected -// case. SequenceMatcher is quadratic time for the worst case and has -// expected-case behavior dependent in a complicated way on how many -// elements the sequences have in common; best case time is linear. -type SequenceMatcher struct { - a []string - b []string - b2j map[string][]int - IsJunk func(string) bool - autoJunk bool - bJunk map[string]struct{} - matchingBlocks []Match - fullBCount map[string]int - bPopular map[string]struct{} - opCodes []OpCode -} - -func NewMatcher(a, b []string) *SequenceMatcher { - m := SequenceMatcher{autoJunk: true} - m.SetSeqs(a, b) - return &m -} - -func NewMatcherWithJunk(a, b []string, autoJunk bool, - isJunk func(string) bool) *SequenceMatcher { - - m := SequenceMatcher{IsJunk: isJunk, autoJunk: autoJunk} - m.SetSeqs(a, b) - return &m -} - -// Set two sequences to be compared. -func (m *SequenceMatcher) SetSeqs(a, b []string) { - m.SetSeq1(a) - m.SetSeq2(b) -} - -// Set the first sequence to be compared. The second sequence to be compared is -// not changed. -// -// SequenceMatcher computes and caches detailed information about the second -// sequence, so if you want to compare one sequence S against many sequences, -// use .SetSeq2(s) once and call .SetSeq1(x) repeatedly for each of the other -// sequences. -// -// See also SetSeqs() and SetSeq2(). -func (m *SequenceMatcher) SetSeq1(a []string) { - if &a == &m.a { - return - } - m.a = a - m.matchingBlocks = nil - m.opCodes = nil -} - -// Set the second sequence to be compared. The first sequence to be compared is -// not changed. -func (m *SequenceMatcher) SetSeq2(b []string) { - if &b == &m.b { - return - } - m.b = b - m.matchingBlocks = nil - m.opCodes = nil - m.fullBCount = nil - m.chainB() -} - -func (m *SequenceMatcher) chainB() { - // Populate line -> index mapping - b2j := map[string][]int{} - for i, s := range m.b { - indices := b2j[s] - indices = append(indices, i) - b2j[s] = indices - } - - // Purge junk elements - m.bJunk = map[string]struct{}{} - if m.IsJunk != nil { - junk := m.bJunk - for s, _ := range b2j { - if m.IsJunk(s) { - junk[s] = struct{}{} - } - } - for s, _ := range junk { - delete(b2j, s) - } - } - - // Purge remaining popular elements - popular := map[string]struct{}{} - n := len(m.b) - if m.autoJunk && n >= 200 { - ntest := n/100 + 1 - for s, indices := range b2j { - if len(indices) > ntest { - popular[s] = struct{}{} - } - } - for s, _ := range popular { - delete(b2j, s) - } - } - m.bPopular = popular - m.b2j = b2j -} - -func (m *SequenceMatcher) isBJunk(s string) bool { - _, ok := m.bJunk[s] - return ok -} - -// Find longest matching block in a[alo:ahi] and b[blo:bhi]. -// -// If IsJunk is not defined: -// -// Return (i,j,k) such that a[i:i+k] is equal to b[j:j+k], where -// alo <= i <= i+k <= ahi -// blo <= j <= j+k <= bhi -// and for all (i',j',k') meeting those conditions, -// k >= k' -// i <= i' -// and if i == i', j <= j' -// -// In other words, of all maximal matching blocks, return one that -// starts earliest in a, and of all those maximal matching blocks that -// start earliest in a, return the one that starts earliest in b. -// -// If IsJunk is defined, first the longest matching block is -// determined as above, but with the additional restriction that no -// junk element appears in the block. Then that block is extended as -// far as possible by matching (only) junk elements on both sides. So -// the resulting block never matches on junk except as identical junk -// happens to be adjacent to an "interesting" match. -// -// If no blocks match, return (alo, blo, 0). -func (m *SequenceMatcher) findLongestMatch(alo, ahi, blo, bhi int) Match { - // CAUTION: stripping common prefix or suffix would be incorrect. - // E.g., - // ab - // acab - // Longest matching block is "ab", but if common prefix is - // stripped, it's "a" (tied with "b"). UNIX(tm) diff does so - // strip, so ends up claiming that ab is changed to acab by - // inserting "ca" in the middle. That's minimal but unintuitive: - // "it's obvious" that someone inserted "ac" at the front. - // Windiff ends up at the same place as diff, but by pairing up - // the unique 'b's and then matching the first two 'a's. - besti, bestj, bestsize := alo, blo, 0 - - // find longest junk-free match - // during an iteration of the loop, j2len[j] = length of longest - // junk-free match ending with a[i-1] and b[j] - j2len := map[int]int{} - for i := alo; i != ahi; i++ { - // look at all instances of a[i] in b; note that because - // b2j has no junk keys, the loop is skipped if a[i] is junk - newj2len := map[int]int{} - for _, j := range m.b2j[m.a[i]] { - // a[i] matches b[j] - if j < blo { - continue - } - if j >= bhi { - break - } - k := j2len[j-1] + 1 - newj2len[j] = k - if k > bestsize { - besti, bestj, bestsize = i-k+1, j-k+1, k - } - } - j2len = newj2len - } - - // Extend the best by non-junk elements on each end. In particular, - // "popular" non-junk elements aren't in b2j, which greatly speeds - // the inner loop above, but also means "the best" match so far - // doesn't contain any junk *or* popular non-junk elements. - for besti > alo && bestj > blo && !m.isBJunk(m.b[bestj-1]) && - m.a[besti-1] == m.b[bestj-1] { - besti, bestj, bestsize = besti-1, bestj-1, bestsize+1 - } - for besti+bestsize < ahi && bestj+bestsize < bhi && - !m.isBJunk(m.b[bestj+bestsize]) && - m.a[besti+bestsize] == m.b[bestj+bestsize] { - bestsize += 1 - } - - // Now that we have a wholly interesting match (albeit possibly - // empty!), we may as well suck up the matching junk on each - // side of it too. Can't think of a good reason not to, and it - // saves post-processing the (possibly considerable) expense of - // figuring out what to do with it. In the case of an empty - // interesting match, this is clearly the right thing to do, - // because no other kind of match is possible in the regions. - for besti > alo && bestj > blo && m.isBJunk(m.b[bestj-1]) && - m.a[besti-1] == m.b[bestj-1] { - besti, bestj, bestsize = besti-1, bestj-1, bestsize+1 - } - for besti+bestsize < ahi && bestj+bestsize < bhi && - m.isBJunk(m.b[bestj+bestsize]) && - m.a[besti+bestsize] == m.b[bestj+bestsize] { - bestsize += 1 - } - - return Match{A: besti, B: bestj, Size: bestsize} -} - -// Return list of triples describing matching subsequences. -// -// Each triple is of the form (i, j, n), and means that -// a[i:i+n] == b[j:j+n]. The triples are monotonically increasing in -// i and in j. It's also guaranteed that if (i, j, n) and (i', j', n') are -// adjacent triples in the list, and the second is not the last triple in the -// list, then i+n != i' or j+n != j'. IOW, adjacent triples never describe -// adjacent equal blocks. -// -// The last triple is a dummy, (len(a), len(b), 0), and is the only -// triple with n==0. -func (m *SequenceMatcher) GetMatchingBlocks() []Match { - if m.matchingBlocks != nil { - return m.matchingBlocks - } - - var matchBlocks func(alo, ahi, blo, bhi int, matched []Match) []Match - matchBlocks = func(alo, ahi, blo, bhi int, matched []Match) []Match { - match := m.findLongestMatch(alo, ahi, blo, bhi) - i, j, k := match.A, match.B, match.Size - if match.Size > 0 { - if alo < i && blo < j { - matched = matchBlocks(alo, i, blo, j, matched) - } - matched = append(matched, match) - if i+k < ahi && j+k < bhi { - matched = matchBlocks(i+k, ahi, j+k, bhi, matched) - } - } - return matched - } - matched := matchBlocks(0, len(m.a), 0, len(m.b), nil) - - // It's possible that we have adjacent equal blocks in the - // matching_blocks list now. - nonAdjacent := []Match{} - i1, j1, k1 := 0, 0, 0 - for _, b := range matched { - // Is this block adjacent to i1, j1, k1? - i2, j2, k2 := b.A, b.B, b.Size - if i1+k1 == i2 && j1+k1 == j2 { - // Yes, so collapse them -- this just increases the length of - // the first block by the length of the second, and the first - // block so lengthened remains the block to compare against. - k1 += k2 - } else { - // Not adjacent. Remember the first block (k1==0 means it's - // the dummy we started with), and make the second block the - // new block to compare against. - if k1 > 0 { - nonAdjacent = append(nonAdjacent, Match{i1, j1, k1}) - } - i1, j1, k1 = i2, j2, k2 - } - } - if k1 > 0 { - nonAdjacent = append(nonAdjacent, Match{i1, j1, k1}) - } - - nonAdjacent = append(nonAdjacent, Match{len(m.a), len(m.b), 0}) - m.matchingBlocks = nonAdjacent - return m.matchingBlocks -} - -// Return list of 5-tuples describing how to turn a into b. -// -// Each tuple is of the form (tag, i1, i2, j1, j2). The first tuple -// has i1 == j1 == 0, and remaining tuples have i1 == the i2 from the -// tuple preceding it, and likewise for j1 == the previous j2. -// -// The tags are characters, with these meanings: -// -// 'r' (replace): a[i1:i2] should be replaced by b[j1:j2] -// -// 'd' (delete): a[i1:i2] should be deleted, j1==j2 in this case. -// -// 'i' (insert): b[j1:j2] should be inserted at a[i1:i1], i1==i2 in this case. -// -// 'e' (equal): a[i1:i2] == b[j1:j2] -func (m *SequenceMatcher) GetOpCodes() []OpCode { - if m.opCodes != nil { - return m.opCodes - } - i, j := 0, 0 - matching := m.GetMatchingBlocks() - opCodes := make([]OpCode, 0, len(matching)) - for _, m := range matching { - // invariant: we've pumped out correct diffs to change - // a[:i] into b[:j], and the next matching block is - // a[ai:ai+size] == b[bj:bj+size]. So we need to pump - // out a diff to change a[i:ai] into b[j:bj], pump out - // the matching block, and move (i,j) beyond the match - ai, bj, size := m.A, m.B, m.Size - tag := byte(0) - if i < ai && j < bj { - tag = 'r' - } else if i < ai { - tag = 'd' - } else if j < bj { - tag = 'i' - } - if tag > 0 { - opCodes = append(opCodes, OpCode{tag, i, ai, j, bj}) - } - i, j = ai+size, bj+size - // the list of matching blocks is terminated by a - // sentinel with size 0 - if size > 0 { - opCodes = append(opCodes, OpCode{'e', ai, i, bj, j}) - } - } - m.opCodes = opCodes - return m.opCodes -} - -// Isolate change clusters by eliminating ranges with no changes. -// -// Return a generator of groups with up to n lines of context. -// Each group is in the same format as returned by GetOpCodes(). -func (m *SequenceMatcher) GetGroupedOpCodes(n int) [][]OpCode { - if n < 0 { - n = 3 - } - codes := m.GetOpCodes() - if len(codes) == 0 { - codes = []OpCode{OpCode{'e', 0, 1, 0, 1}} - } - // Fixup leading and trailing groups if they show no changes. - if codes[0].Tag == 'e' { - c := codes[0] - i1, i2, j1, j2 := c.I1, c.I2, c.J1, c.J2 - codes[0] = OpCode{c.Tag, max(i1, i2-n), i2, max(j1, j2-n), j2} - } - if codes[len(codes)-1].Tag == 'e' { - c := codes[len(codes)-1] - i1, i2, j1, j2 := c.I1, c.I2, c.J1, c.J2 - codes[len(codes)-1] = OpCode{c.Tag, i1, min(i2, i1+n), j1, min(j2, j1+n)} - } - nn := n + n - groups := [][]OpCode{} - group := []OpCode{} - for _, c := range codes { - i1, i2, j1, j2 := c.I1, c.I2, c.J1, c.J2 - // End the current group and start a new one whenever - // there is a large range with no changes. - if c.Tag == 'e' && i2-i1 > nn { - group = append(group, OpCode{c.Tag, i1, min(i2, i1+n), - j1, min(j2, j1+n)}) - groups = append(groups, group) - group = []OpCode{} - i1, j1 = max(i1, i2-n), max(j1, j2-n) - } - group = append(group, OpCode{c.Tag, i1, i2, j1, j2}) - } - if len(group) > 0 && !(len(group) == 1 && group[0].Tag == 'e') { - groups = append(groups, group) - } - return groups -} - -// Return a measure of the sequences' similarity (float in [0,1]). -// -// Where T is the total number of elements in both sequences, and -// M is the number of matches, this is 2.0*M / T. -// Note that this is 1 if the sequences are identical, and 0 if -// they have nothing in common. -// -// .Ratio() is expensive to compute if you haven't already computed -// .GetMatchingBlocks() or .GetOpCodes(), in which case you may -// want to try .QuickRatio() or .RealQuickRation() first to get an -// upper bound. -func (m *SequenceMatcher) Ratio() float64 { - matches := 0 - for _, m := range m.GetMatchingBlocks() { - matches += m.Size - } - return calculateRatio(matches, len(m.a)+len(m.b)) -} - -// Return an upper bound on ratio() relatively quickly. -// -// This isn't defined beyond that it is an upper bound on .Ratio(), and -// is faster to compute. -func (m *SequenceMatcher) QuickRatio() float64 { - // viewing a and b as multisets, set matches to the cardinality - // of their intersection; this counts the number of matches - // without regard to order, so is clearly an upper bound - if m.fullBCount == nil { - m.fullBCount = map[string]int{} - for _, s := range m.b { - m.fullBCount[s] = m.fullBCount[s] + 1 - } - } - - // avail[x] is the number of times x appears in 'b' less the - // number of times we've seen it in 'a' so far ... kinda - avail := map[string]int{} - matches := 0 - for _, s := range m.a { - n, ok := avail[s] - if !ok { - n = m.fullBCount[s] - } - avail[s] = n - 1 - if n > 0 { - matches += 1 - } - } - return calculateRatio(matches, len(m.a)+len(m.b)) -} - -// Return an upper bound on ratio() very quickly. -// -// This isn't defined beyond that it is an upper bound on .Ratio(), and -// is faster to compute than either .Ratio() or .QuickRatio(). -func (m *SequenceMatcher) RealQuickRatio() float64 { - la, lb := len(m.a), len(m.b) - return calculateRatio(min(la, lb), la+lb) -} - -// Convert range to the "ed" format -func formatRangeUnified(start, stop int) string { - // Per the diff spec at http://www.unix.org/single_unix_specification/ - beginning := start + 1 // lines start numbering with one - length := stop - start - if length == 1 { - return fmt.Sprintf("%d", beginning) - } - if length == 0 { - beginning -= 1 // empty ranges begin at line just before the range - } - return fmt.Sprintf("%d,%d", beginning, length) -} - -// Unified diff parameters -type UnifiedDiff struct { - A []string // First sequence lines - FromFile string // First file name - FromDate string // First file time - B []string // Second sequence lines - ToFile string // Second file name - ToDate string // Second file time - Eol string // Headers end of line, defaults to LF - Context int // Number of context lines -} - -// Compare two sequences of lines; generate the delta as a unified diff. -// -// Unified diffs are a compact way of showing line changes and a few -// lines of context. The number of context lines is set by 'n' which -// defaults to three. -// -// By default, the diff control lines (those with ---, +++, or @@) are -// created with a trailing newline. This is helpful so that inputs -// created from file.readlines() result in diffs that are suitable for -// file.writelines() since both the inputs and outputs have trailing -// newlines. -// -// For inputs that do not have trailing newlines, set the lineterm -// argument to "" so that the output will be uniformly newline free. -// -// The unidiff format normally has a header for filenames and modification -// times. Any or all of these may be specified using strings for -// 'fromfile', 'tofile', 'fromfiledate', and 'tofiledate'. -// The modification times are normally expressed in the ISO 8601 format. -func WriteUnifiedDiff(writer io.Writer, diff UnifiedDiff) error { - buf := bufio.NewWriter(writer) - defer buf.Flush() - w := func(format string, args ...interface{}) error { - _, err := buf.WriteString(fmt.Sprintf(format, args...)) - return err - } - - if len(diff.Eol) == 0 { - diff.Eol = "\n" - } - - started := false - m := NewMatcher(diff.A, diff.B) - for _, g := range m.GetGroupedOpCodes(diff.Context) { - if !started { - started = true - fromDate := "" - if len(diff.FromDate) > 0 { - fromDate = "\t" + diff.FromDate - } - toDate := "" - if len(diff.ToDate) > 0 { - toDate = "\t" + diff.ToDate - } - err := w("--- %s%s%s", diff.FromFile, fromDate, diff.Eol) - if err != nil { - return err - } - err = w("+++ %s%s%s", diff.ToFile, toDate, diff.Eol) - if err != nil { - return err - } - } - first, last := g[0], g[len(g)-1] - range1 := formatRangeUnified(first.I1, last.I2) - range2 := formatRangeUnified(first.J1, last.J2) - if err := w("@@ -%s +%s @@%s", range1, range2, diff.Eol); err != nil { - return err - } - for _, c := range g { - i1, i2, j1, j2 := c.I1, c.I2, c.J1, c.J2 - if c.Tag == 'e' { - for _, line := range diff.A[i1:i2] { - if err := w(" " + line); err != nil { - return err - } - } - continue - } - if c.Tag == 'r' || c.Tag == 'd' { - for _, line := range diff.A[i1:i2] { - if err := w("-" + line); err != nil { - return err - } - } - } - if c.Tag == 'r' || c.Tag == 'i' { - for _, line := range diff.B[j1:j2] { - if err := w("+" + line); err != nil { - return err - } - } - } - } - } - return nil -} - -// Like WriteUnifiedDiff but returns the diff a string. -func GetUnifiedDiffString(diff UnifiedDiff) (string, error) { - w := &bytes.Buffer{} - err := WriteUnifiedDiff(w, diff) - return string(w.Bytes()), err -} - -// Convert range to the "ed" format. -func formatRangeContext(start, stop int) string { - // Per the diff spec at http://www.unix.org/single_unix_specification/ - beginning := start + 1 // lines start numbering with one - length := stop - start - if length == 0 { - beginning -= 1 // empty ranges begin at line just before the range - } - if length <= 1 { - return fmt.Sprintf("%d", beginning) - } - return fmt.Sprintf("%d,%d", beginning, beginning+length-1) -} - -type ContextDiff UnifiedDiff - -// Compare two sequences of lines; generate the delta as a context diff. -// -// Context diffs are a compact way of showing line changes and a few -// lines of context. The number of context lines is set by diff.Context -// which defaults to three. -// -// By default, the diff control lines (those with *** or ---) are -// created with a trailing newline. -// -// For inputs that do not have trailing newlines, set the diff.Eol -// argument to "" so that the output will be uniformly newline free. -// -// The context diff format normally has a header for filenames and -// modification times. Any or all of these may be specified using -// strings for diff.FromFile, diff.ToFile, diff.FromDate, diff.ToDate. -// The modification times are normally expressed in the ISO 8601 format. -// If not specified, the strings default to blanks. -func WriteContextDiff(writer io.Writer, diff ContextDiff) error { - buf := bufio.NewWriter(writer) - defer buf.Flush() - var diffErr error - w := func(format string, args ...interface{}) { - _, err := buf.WriteString(fmt.Sprintf(format, args...)) - if diffErr == nil && err != nil { - diffErr = err - } - } - - if len(diff.Eol) == 0 { - diff.Eol = "\n" - } - - prefix := map[byte]string{ - 'i': "+ ", - 'd': "- ", - 'r': "! ", - 'e': " ", - } - - started := false - m := NewMatcher(diff.A, diff.B) - for _, g := range m.GetGroupedOpCodes(diff.Context) { - if !started { - started = true - fromDate := "" - if len(diff.FromDate) > 0 { - fromDate = "\t" + diff.FromDate - } - toDate := "" - if len(diff.ToDate) > 0 { - toDate = "\t" + diff.ToDate - } - w("*** %s%s%s", diff.FromFile, fromDate, diff.Eol) - w("--- %s%s%s", diff.ToFile, toDate, diff.Eol) - } - - first, last := g[0], g[len(g)-1] - w("***************" + diff.Eol) - - range1 := formatRangeContext(first.I1, last.I2) - w("*** %s ****%s", range1, diff.Eol) - for _, c := range g { - if c.Tag == 'r' || c.Tag == 'd' { - for _, cc := range g { - if cc.Tag == 'i' { - continue - } - for _, line := range diff.A[cc.I1:cc.I2] { - w(prefix[cc.Tag] + line) - } - } - break - } - } - - range2 := formatRangeContext(first.J1, last.J2) - w("--- %s ----%s", range2, diff.Eol) - for _, c := range g { - if c.Tag == 'r' || c.Tag == 'i' { - for _, cc := range g { - if cc.Tag == 'd' { - continue - } - for _, line := range diff.B[cc.J1:cc.J2] { - w(prefix[cc.Tag] + line) - } - } - break - } - } - } - return diffErr -} - -// Like WriteContextDiff but returns the diff a string. -func GetContextDiffString(diff ContextDiff) (string, error) { - w := &bytes.Buffer{} - err := WriteContextDiff(w, diff) - return string(w.Bytes()), err -} - -// Split a string on "\n" while preserving them. The output can be used -// as input for UnifiedDiff and ContextDiff structures. -func SplitLines(s string) []string { - lines := strings.SplitAfter(s, "\n") - lines[len(lines)-1] += "\n" - return lines -} diff --git a/vendor/github.com/spf13/afero/README.md b/vendor/github.com/spf13/afero/README.md index db20817..d9e3327 100644 --- a/vendor/github.com/spf13/afero/README.md +++ b/vendor/github.com/spf13/afero/README.md @@ -198,17 +198,17 @@ independent, with no test relying on the state left by an earlier test. Then in my tests I would initialize a new MemMapFs for each test: ```go func TestExist(t *testing.T) { - appFS = afero.NewMemMapFs() + appFS := afero.NewMemMapFs() // create test files and directories - appFS.MkdirAll("src/a", 0755)) + appFS.MkdirAll("src/a", 0755) afero.WriteFile(appFS, "src/a/b", []byte("file b"), 0644) afero.WriteFile(appFS, "src/c", []byte("file c"), 0644) - _, err := appFS.Stat("src/c") + name := "src/c" + _, err := appFS.Stat(name) if os.IsNotExist(err) { - t.Errorf("file \"%s\" does not exist.\n", name) + t.Errorf("file \"%s\" does not exist.\n", name) } } - ``` # Available Backends diff --git a/vendor/github.com/spf13/afero/afero.go b/vendor/github.com/spf13/afero/afero.go index e3df3f4..f5b5e12 100644 --- a/vendor/github.com/spf13/afero/afero.go +++ b/vendor/github.com/spf13/afero/afero.go @@ -77,7 +77,7 @@ type Fs interface { // happens. Remove(name string) error - // RemoveAll removes a directory path and all any children it contains. It + // RemoveAll removes a directory path and any children it contains. It // does not fail if the path does not exist (return nil). RemoveAll(path string) error diff --git a/vendor/github.com/spf13/afero/basepath.go b/vendor/github.com/spf13/afero/basepath.go index 6ec6ca9..5e4fc2e 100644 --- a/vendor/github.com/spf13/afero/basepath.go +++ b/vendor/github.com/spf13/afero/basepath.go @@ -52,7 +52,7 @@ func validateBasePathName(name string) error { // On Windows a common mistake would be to provide an absolute OS path // We could strip out the base part, but that would not be very portable. if filepath.IsAbs(name) { - return &os.PathError{"realPath", name, errors.New("got a real OS path instead of a virtual")} + return &os.PathError{Op: "realPath", Path: name, Err: errors.New("got a real OS path instead of a virtual")} } return nil @@ -60,14 +60,14 @@ func validateBasePathName(name string) error { func (b *BasePathFs) Chtimes(name string, atime, mtime time.Time) (err error) { if name, err = b.RealPath(name); err != nil { - return &os.PathError{"chtimes", name, err} + return &os.PathError{Op: "chtimes", Path: name, Err: err} } return b.source.Chtimes(name, atime, mtime) } func (b *BasePathFs) Chmod(name string, mode os.FileMode) (err error) { if name, err = b.RealPath(name); err != nil { - return &os.PathError{"chmod", name, err} + return &os.PathError{Op: "chmod", Path: name, Err: err} } return b.source.Chmod(name, mode) } @@ -78,66 +78,66 @@ func (b *BasePathFs) Name() string { func (b *BasePathFs) Stat(name string) (fi os.FileInfo, err error) { if name, err = b.RealPath(name); err != nil { - return nil, &os.PathError{"stat", name, err} + return nil, &os.PathError{Op: "stat", Path: name, Err: err} } return b.source.Stat(name) } func (b *BasePathFs) Rename(oldname, newname string) (err error) { if oldname, err = b.RealPath(oldname); err != nil { - return &os.PathError{"rename", oldname, err} + return &os.PathError{Op: "rename", Path: oldname, Err: err} } if newname, err = b.RealPath(newname); err != nil { - return &os.PathError{"rename", newname, err} + return &os.PathError{Op: "rename", Path: newname, Err: err} } return b.source.Rename(oldname, newname) } func (b *BasePathFs) RemoveAll(name string) (err error) { if name, err = b.RealPath(name); err != nil { - return &os.PathError{"remove_all", name, err} + return &os.PathError{Op: "remove_all", Path: name, Err: err} } return b.source.RemoveAll(name) } func (b *BasePathFs) Remove(name string) (err error) { if name, err = b.RealPath(name); err != nil { - return &os.PathError{"remove", name, err} + return &os.PathError{Op: "remove", Path: name, Err: err} } return b.source.Remove(name) } func (b *BasePathFs) OpenFile(name string, flag int, mode os.FileMode) (f File, err error) { if name, err = b.RealPath(name); err != nil { - return nil, &os.PathError{"openfile", name, err} + return nil, &os.PathError{Op: "openfile", Path: name, Err: err} } return b.source.OpenFile(name, flag, mode) } func (b *BasePathFs) Open(name string) (f File, err error) { if name, err = b.RealPath(name); err != nil { - return nil, &os.PathError{"open", name, err} + return nil, &os.PathError{Op: "open", Path: name, Err: err} } return b.source.Open(name) } func (b *BasePathFs) Mkdir(name string, mode os.FileMode) (err error) { if name, err = b.RealPath(name); err != nil { - return &os.PathError{"mkdir", name, err} + return &os.PathError{Op: "mkdir", Path: name, Err: err} } return b.source.Mkdir(name, mode) } func (b *BasePathFs) MkdirAll(name string, mode os.FileMode) (err error) { if name, err = b.RealPath(name); err != nil { - return &os.PathError{"mkdir", name, err} + return &os.PathError{Op: "mkdir", Path: name, Err: err} } return b.source.MkdirAll(name, mode) } func (b *BasePathFs) Create(name string) (f File, err error) { if name, err = b.RealPath(name); err != nil { - return nil, &os.PathError{"create", name, err} + return nil, &os.PathError{Op: "create", Path: name, Err: err} } return b.source.Create(name) } diff --git a/vendor/github.com/spf13/afero/cacheOnReadFs.go b/vendor/github.com/spf13/afero/cacheOnReadFs.go index d742425..e54a4f8 100644 --- a/vendor/github.com/spf13/afero/cacheOnReadFs.go +++ b/vendor/github.com/spf13/afero/cacheOnReadFs.go @@ -32,9 +32,8 @@ func NewCacheOnReadFs(base Fs, layer Fs, cacheTime time.Duration) Fs { type cacheState int const ( - cacheUnknown cacheState = iota // not present in the overlay, unknown if it exists in the base: - cacheMiss + cacheMiss cacheState = iota // present in the overlay and in base, base file is newer: cacheStale // present in the overlay - with cache time == 0 it may exist in the base, diff --git a/vendor/github.com/spf13/afero/mem/file.go b/vendor/github.com/spf13/afero/mem/file.go index 3c1e09a..e41e012 100644 --- a/vendor/github.com/spf13/afero/mem/file.go +++ b/vendor/github.com/spf13/afero/mem/file.go @@ -186,7 +186,7 @@ func (f *File) Truncate(size int64) error { return ErrFileClosed } if f.readOnly { - return &os.PathError{"truncate", f.fileData.name, errors.New("file handle is read only")} + return &os.PathError{Op: "truncate", Path: f.fileData.name, Err: errors.New("file handle is read only")} } if size < 0 { return ErrOutOfRange @@ -218,7 +218,7 @@ func (f *File) Seek(offset int64, whence int) (int64, error) { func (f *File) Write(b []byte) (n int, err error) { if f.readOnly { - return 0, &os.PathError{"write", f.fileData.name, errors.New("file handle is read only")} + return 0, &os.PathError{Op: "write", Path: f.fileData.name, Err: errors.New("file handle is read only")} } n = len(b) cur := atomic.LoadInt64(&f.at) diff --git a/vendor/github.com/spf13/afero/memmap.go b/vendor/github.com/spf13/afero/memmap.go index 2e259b8..767ac1d 100644 --- a/vendor/github.com/spf13/afero/memmap.go +++ b/vendor/github.com/spf13/afero/memmap.go @@ -35,8 +35,6 @@ func NewMemMapFs() Fs { return &MemMapFs{} } -var memfsInit sync.Once - func (m *MemMapFs) getData() map[string]*mem.FileData { m.init.Do(func() { m.data = make(map[string]*mem.FileData) @@ -47,7 +45,7 @@ func (m *MemMapFs) getData() map[string]*mem.FileData { return m.data } -func (MemMapFs) Name() string { return "MemMapFS" } +func (*MemMapFs) Name() string { return "MemMapFS" } func (m *MemMapFs) Create(name string) (File, error) { name = normalizePath(name) @@ -110,7 +108,7 @@ func (m *MemMapFs) lockfreeMkdir(name string, perm os.FileMode) error { x, ok := m.getData()[name] if ok { // Only return ErrFileExists if it's a file, not a directory. - i := mem.FileInfo{x} + i := mem.FileInfo{FileData: x} if !i.IsDir() { return ErrFileExists } @@ -129,14 +127,17 @@ func (m *MemMapFs) Mkdir(name string, perm os.FileMode) error { _, ok := m.getData()[name] m.mu.RUnlock() if ok { - return &os.PathError{"mkdir", name, ErrFileExists} - } else { - m.mu.Lock() - item := mem.CreateDir(name) - m.getData()[name] = item - m.registerWithParent(item) - m.mu.Unlock() + return &os.PathError{Op: "mkdir", Path: name, Err: ErrFileExists} } + + m.mu.Lock() + item := mem.CreateDir(name) + m.getData()[name] = item + m.registerWithParent(item) + m.mu.Unlock() + + m.Chmod(name, perm) + return nil } @@ -189,7 +190,7 @@ func (m *MemMapFs) open(name string) (*mem.FileData, error) { f, ok := m.getData()[name] m.mu.RUnlock() if !ok { - return nil, &os.PathError{"open", name, ErrFileNotFound} + return nil, &os.PathError{Op: "open", Path: name, Err: ErrFileNotFound} } return f, nil } @@ -205,9 +206,11 @@ func (m *MemMapFs) lockfreeOpen(name string) (*mem.FileData, error) { } func (m *MemMapFs) OpenFile(name string, flag int, perm os.FileMode) (File, error) { + chmod := false file, err := m.openWrite(name) if os.IsNotExist(err) && (flag&os.O_CREATE > 0) { file, err = m.Create(name) + chmod = true } if err != nil { return nil, err @@ -229,6 +232,9 @@ func (m *MemMapFs) OpenFile(name string, flag int, perm os.FileMode) (File, erro return nil, err } } + if chmod { + m.Chmod(name, perm) + } return file, nil } @@ -241,11 +247,11 @@ func (m *MemMapFs) Remove(name string) error { if _, ok := m.getData()[name]; ok { err := m.unRegisterWithParent(name) if err != nil { - return &os.PathError{"remove", name, err} + return &os.PathError{Op: "remove", Path: name, Err: err} } delete(m.getData(), name) } else { - return &os.PathError{"remove", name, os.ErrNotExist} + return &os.PathError{Op: "remove", Path: name, Err: os.ErrNotExist} } return nil } @@ -293,7 +299,7 @@ func (m *MemMapFs) Rename(oldname, newname string) error { m.mu.Unlock() m.mu.RLock() } else { - return &os.PathError{"rename", oldname, ErrFileNotFound} + return &os.PathError{Op: "rename", Path: oldname, Err: ErrFileNotFound} } return nil } @@ -309,9 +315,12 @@ func (m *MemMapFs) Stat(name string) (os.FileInfo, error) { func (m *MemMapFs) Chmod(name string, mode os.FileMode) error { name = normalizePath(name) + + m.mu.RLock() f, ok := m.getData()[name] + m.mu.RUnlock() if !ok { - return &os.PathError{"chmod", name, ErrFileNotFound} + return &os.PathError{Op: "chmod", Path: name, Err: ErrFileNotFound} } m.mu.Lock() @@ -323,9 +332,12 @@ func (m *MemMapFs) Chmod(name string, mode os.FileMode) error { func (m *MemMapFs) Chtimes(name string, atime time.Time, mtime time.Time) error { name = normalizePath(name) + + m.mu.RLock() f, ok := m.getData()[name] + m.mu.RUnlock() if !ok { - return &os.PathError{"chtimes", name, ErrFileNotFound} + return &os.PathError{Op: "chtimes", Path: name, Err: ErrFileNotFound} } m.mu.Lock() @@ -337,13 +349,13 @@ func (m *MemMapFs) Chtimes(name string, atime time.Time, mtime time.Time) error func (m *MemMapFs) List() { for _, x := range m.data { - y := mem.FileInfo{x} + y := mem.FileInfo{FileData: x} fmt.Println(x.Name(), y.Size()) } } -func debugMemMapList(fs Fs) { - if x, ok := fs.(*MemMapFs); ok { - x.List() - } -} +// func debugMemMapList(fs Fs) { +// if x, ok := fs.(*MemMapFs); ok { +// x.List() +// } +// } diff --git a/vendor/github.com/spf13/afero/sftp.go b/vendor/github.com/spf13/afero/sftp.go deleted file mode 100644 index a095a54..0000000 --- a/vendor/github.com/spf13/afero/sftp.go +++ /dev/null @@ -1,128 +0,0 @@ -// Copyright © 2015 Jerry Jacobs . -// -// 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 afero - -import ( - "os" - "time" - - "github.com/spf13/afero/sftp" - - "github.com/pkg/sftp" -) - -// SftpFs is a Fs implementation that uses functions provided by the sftp package. -// -// For details in any method, check the documentation of the sftp package -// (github.com/pkg/sftp). -type SftpFs struct{ - SftpClient *sftp.Client -} - -func (s SftpFs) Name() string { return "SftpFs" } - -func (s SftpFs) Create(name string) (File, error) { - f, err := sftpfs.FileCreate(s.SftpClient, name) - return f, err -} - -func (s SftpFs) Mkdir(name string, perm os.FileMode) error { - err := s.SftpClient.Mkdir(name) - if err != nil { - return err - } - return s.SftpClient.Chmod(name, perm) -} - -func (s SftpFs) MkdirAll(path string, perm os.FileMode) error { - // Fast path: if we can tell whether path is a directory or file, stop with success or error. - dir, err := s.Stat(path) - if err == nil { - if dir.IsDir() { - return nil - } - return err - } - - // Slow path: make sure parent exists and then call Mkdir for path. - i := len(path) - for i > 0 && os.IsPathSeparator(path[i-1]) { // Skip trailing path separator. - i-- - } - - j := i - for j > 0 && !os.IsPathSeparator(path[j-1]) { // Scan backward over element. - j-- - } - - if j > 1 { - // Create parent - err = s.MkdirAll(path[0:j-1], perm) - if err != nil { - return err - } - } - - // Parent now exists; invoke Mkdir and use its result. - err = s.Mkdir(path, perm) - if err != nil { - // Handle arguments like "foo/." by - // double-checking that directory doesn't exist. - dir, err1 := s.Lstat(path) - if err1 == nil && dir.IsDir() { - return nil - } - return err - } - return nil -} - -func (s SftpFs) Open(name string) (File, error) { - f, err := sftpfs.FileOpen(s.SftpClient, name) - return f, err -} - -func (s SftpFs) OpenFile(name string, flag int, perm os.FileMode) (File, error) { - return nil,nil -} - -func (s SftpFs) Remove(name string) error { - return s.SftpClient.Remove(name) -} - -func (s SftpFs) RemoveAll(path string) error { - // TODO have a look at os.RemoveAll - // https://github.com/golang/go/blob/master/src/os/path.go#L66 - return nil -} - -func (s SftpFs) Rename(oldname, newname string) error { - return s.SftpClient.Rename(oldname, newname) -} - -func (s SftpFs) Stat(name string) (os.FileInfo, error) { - return s.SftpClient.Stat(name) -} - -func (s SftpFs) Lstat(p string) (os.FileInfo, error) { - return s.SftpClient.Lstat(p) -} - -func (s SftpFs) Chmod(name string, mode os.FileMode) error { - return s.SftpClient.Chmod(name, mode) -} - -func (s SftpFs) Chtimes(name string, atime time.Time, mtime time.Time) error { - return s.SftpClient.Chtimes(name, atime, mtime) -} diff --git a/vendor/github.com/spf13/afero/sftp/file.go b/vendor/github.com/spf13/afero/sftp/file.go deleted file mode 100644 index bab4abc..0000000 --- a/vendor/github.com/spf13/afero/sftp/file.go +++ /dev/null @@ -1,95 +0,0 @@ -// Copyright © 2015 Jerry Jacobs . -// -// 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 sftpfs - -import ( - "os" - "github.com/pkg/sftp" -) - -type File struct { - fd *sftp.File -} - -func FileOpen(s *sftp.Client, name string) (*File, error) { - fd, err := s.Open(name) - if err != nil { - return &File{}, err - } - return &File{fd: fd}, nil -} - -func FileCreate(s *sftp.Client, name string) (*File, error) { - fd, err := s.Create(name) - if err != nil { - return &File{}, err - } - return &File{fd: fd}, nil -} - -func (f *File) Close() error { - return f.fd.Close() -} - -func (f *File) Name() string { - return f.fd.Name() -} - -func (f *File) Stat() (os.FileInfo, error) { - return f.fd.Stat() -} - -func (f *File) Sync() error { - return nil -} - -func (f *File) Truncate(size int64) error { - return f.fd.Truncate(size) -} - -func (f *File) Read(b []byte) (n int, err error) { - return f.fd.Read(b) -} - -// TODO -func (f *File) ReadAt(b []byte, off int64) (n int, err error) { - return 0,nil -} - -// TODO -func (f *File) Readdir(count int) (res []os.FileInfo, err error) { - return nil,nil -} - -// TODO -func (f *File) Readdirnames(n int) (names []string, err error) { - return nil,nil -} - -func (f *File) Seek(offset int64, whence int) (int64, error) { - return f.fd.Seek(offset, whence) -} - -func (f *File) Write(b []byte) (n int, err error) { - return f.fd.Write(b) -} - -// TODO -func (f *File) WriteAt(b []byte, off int64) (n int, err error) { - return 0,nil -} - -func (f *File) WriteString(s string) (ret int, err error) { - return f.fd.Write([]byte(s)) -} diff --git a/vendor/github.com/spf13/afero/sftp_test_go b/vendor/github.com/spf13/afero/sftp_test_go deleted file mode 100644 index bb00535..0000000 --- a/vendor/github.com/spf13/afero/sftp_test_go +++ /dev/null @@ -1,286 +0,0 @@ -// Copyright © 2015 Jerry Jacobs . -// -// 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 afero - -import ( - "testing" - "os" - "log" - "fmt" - "net" - "flag" - "time" - "io/ioutil" - "crypto/rsa" - _rand "crypto/rand" - "encoding/pem" - "crypto/x509" - - "golang.org/x/crypto/ssh" - "github.com/pkg/sftp" -) - -type SftpFsContext struct { - sshc *ssh.Client - sshcfg *ssh.ClientConfig - sftpc *sftp.Client -} - -// TODO we only connect with hardcoded user+pass for now -// it should be possible to use $HOME/.ssh/id_rsa to login into the stub sftp server -func SftpConnect(user, password, host string) (*SftpFsContext, error) { -/* - pemBytes, err := ioutil.ReadFile(os.Getenv("HOME") + "/.ssh/id_rsa") - if err != nil { - return nil,err - } - - signer, err := ssh.ParsePrivateKey(pemBytes) - if err != nil { - return nil,err - } - - sshcfg := &ssh.ClientConfig{ - User: user, - Auth: []ssh.AuthMethod{ - ssh.Password(password), - ssh.PublicKeys(signer), - }, - } -*/ - - sshcfg := &ssh.ClientConfig{ - User: user, - Auth: []ssh.AuthMethod{ - ssh.Password(password), - }, - } - - sshc, err := ssh.Dial("tcp", host, sshcfg) - if err != nil { - return nil,err - } - - sftpc, err := sftp.NewClient(sshc) - if err != nil { - return nil,err - } - - ctx := &SftpFsContext{ - sshc: sshc, - sshcfg: sshcfg, - sftpc: sftpc, - } - - return ctx,nil -} - -func (ctx *SftpFsContext) Disconnect() error { - ctx.sftpc.Close() - ctx.sshc.Close() - return nil -} - -// TODO for such a weird reason rootpath is "." when writing "file1" with afero sftp backend -func RunSftpServer(rootpath string) { - var ( - readOnly bool - debugLevelStr string - debugLevel int - debugStderr bool - rootDir string - ) - - flag.BoolVar(&readOnly, "R", false, "read-only server") - flag.BoolVar(&debugStderr, "e", true, "debug to stderr") - flag.StringVar(&debugLevelStr, "l", "none", "debug level") - flag.StringVar(&rootDir, "root", rootpath, "root directory") - flag.Parse() - - debugStream := ioutil.Discard - if debugStderr { - debugStream = os.Stderr - debugLevel = 1 - } - - // An SSH server is represented by a ServerConfig, which holds - // certificate details and handles authentication of ServerConns. - config := &ssh.ServerConfig{ - PasswordCallback: func(c ssh.ConnMetadata, pass []byte) (*ssh.Permissions, error) { - // Should use constant-time compare (or better, salt+hash) in - // a production setting. - fmt.Fprintf(debugStream, "Login: %s\n", c.User()) - if c.User() == "test" && string(pass) == "test" { - return nil, nil - } - return nil, fmt.Errorf("password rejected for %q", c.User()) - }, - } - - privateBytes, err := ioutil.ReadFile("./test/id_rsa") - if err != nil { - log.Fatal("Failed to load private key", err) - } - - private, err := ssh.ParsePrivateKey(privateBytes) - if err != nil { - log.Fatal("Failed to parse private key", err) - } - - config.AddHostKey(private) - - // Once a ServerConfig has been configured, connections can be - // accepted. - listener, err := net.Listen("tcp", "0.0.0.0:2022") - if err != nil { - log.Fatal("failed to listen for connection", err) - } - fmt.Printf("Listening on %v\n", listener.Addr()) - - nConn, err := listener.Accept() - if err != nil { - log.Fatal("failed to accept incoming connection", err) - } - - // Before use, a handshake must be performed on the incoming - // net.Conn. - _, chans, reqs, err := ssh.NewServerConn(nConn, config) - if err != nil { - log.Fatal("failed to handshake", err) - } - fmt.Fprintf(debugStream, "SSH server established\n") - - // The incoming Request channel must be serviced. - go ssh.DiscardRequests(reqs) - - // Service the incoming Channel channel. - for newChannel := range chans { - // Channels have a type, depending on the application level - // protocol intended. In the case of an SFTP session, this is "subsystem" - // with a payload string of "sftp" - fmt.Fprintf(debugStream, "Incoming channel: %s\n", newChannel.ChannelType()) - if newChannel.ChannelType() != "session" { - newChannel.Reject(ssh.UnknownChannelType, "unknown channel type") - fmt.Fprintf(debugStream, "Unknown channel type: %s\n", newChannel.ChannelType()) - continue - } - channel, requests, err := newChannel.Accept() - if err != nil { - log.Fatal("could not accept channel.", err) - } - fmt.Fprintf(debugStream, "Channel accepted\n") - - // Sessions have out-of-band requests such as "shell", - // "pty-req" and "env". Here we handle only the - // "subsystem" request. - go func(in <-chan *ssh.Request) { - for req := range in { - fmt.Fprintf(debugStream, "Request: %v\n", req.Type) - ok := false - switch req.Type { - case "subsystem": - fmt.Fprintf(debugStream, "Subsystem: %s\n", req.Payload[4:]) - if string(req.Payload[4:]) == "sftp" { - ok = true - } - } - fmt.Fprintf(debugStream, " - accepted: %v\n", ok) - req.Reply(ok, nil) - } - }(requests) - - server, err := sftp.NewServer(channel, channel, debugStream, debugLevel, readOnly, rootpath) - if err != nil { - log.Fatal(err) - } - if err := server.Serve(); err != nil { - log.Fatal("sftp server completed with error:", err) - } - } -} - -// MakeSSHKeyPair make a pair of public and private keys for SSH access. -// Public key is encoded in the format for inclusion in an OpenSSH authorized_keys file. -// Private Key generated is PEM encoded -func MakeSSHKeyPair(bits int, pubKeyPath, privateKeyPath string) error { - privateKey, err := rsa.GenerateKey(_rand.Reader, bits) - if err != nil { - return err - } - - // generate and write private key as PEM - privateKeyFile, err := os.Create(privateKeyPath) - defer privateKeyFile.Close() - if err != nil { - return err - } - - privateKeyPEM := &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(privateKey)} - if err := pem.Encode(privateKeyFile, privateKeyPEM); err != nil { - return err - } - - // generate and write public key - pub, err := ssh.NewPublicKey(&privateKey.PublicKey) - if err != nil { - return err - } - - return ioutil.WriteFile(pubKeyPath, ssh.MarshalAuthorizedKey(pub), 0655) -} - -func TestSftpCreate(t *testing.T) { - os.Mkdir("./test", 0777) - MakeSSHKeyPair(1024, "./test/id_rsa.pub", "./test/id_rsa") - - go RunSftpServer("./test/") - time.Sleep(5 * time.Second) - - ctx, err := SftpConnect("test", "test", "localhost:2022") - if err != nil { - t.Fatal(err) - } - defer ctx.Disconnect() - - var AppFs Fs = SftpFs{ - SftpClient: ctx.sftpc, - } - - AppFs.MkdirAll("test/dir1/dir2/dir3", os.FileMode(0777)) - AppFs.Mkdir("test/foo", os.FileMode(0000)) - AppFs.Chmod("test/foo", os.FileMode(0700)) - AppFs.Mkdir("test/bar", os.FileMode(0777)) - - file, err := AppFs.Create("file1") - if err != nil { - t.Error(err) - } - defer file.Close() - - file.Write([]byte("hello\t")) - file.WriteString("world!\n") - - f1, err := AppFs.Open("file1") - if err != nil { - log.Fatalf("open: %v", err) - } - defer f1.Close() - - b := make([]byte, 100) - - _, err = f1.Read(b) - fmt.Println(string(b)) - - // TODO check here if "hello\tworld\n" is in buffer b -} diff --git a/vendor/github.com/spf13/cast/caste.go b/vendor/github.com/spf13/cast/caste.go index 23f59a1..1aaa1ff 100644 --- a/vendor/github.com/spf13/cast/caste.go +++ b/vendor/github.com/spf13/cast/caste.go @@ -18,15 +18,21 @@ import ( func ToTimeE(i interface{}) (tim time.Time, err error) { i = indirect(i) - switch s := i.(type) { + switch v := i.(type) { case time.Time: - return s, nil + return v, nil case string: - d, e := StringToDate(s) + d, e := StringToDate(v) if e == nil { return d, nil } return time.Time{}, fmt.Errorf("Could not parse Date/Time format: %v\n", e) + case int: + return time.Unix(int64(v), 0), nil + case int32: + return time.Unix(int64(v), 0), nil + case int64: + return time.Unix(v, 0), nil default: return time.Time{}, fmt.Errorf("Unable to Cast %#v to Time\n", i) } @@ -513,6 +519,7 @@ func StringToDate(s string) (time.Time, error) { "02 Jan 2006", "2006-01-02 15:04:05 -07:00", "2006-01-02 15:04:05 -0700", + "2006-01-02 15:04:05", }) } diff --git a/vendor/github.com/spf13/cobra/README.md b/vendor/github.com/spf13/cobra/README.md index 5d2504b..2efda59 100644 --- a/vendor/github.com/spf13/cobra/README.md +++ b/vendor/github.com/spf13/cobra/README.md @@ -157,7 +157,12 @@ In a Cobra app, typically the main.go file is very bare. It serves, one purpose, ```go package main -import "{pathToYourApp}/cmd" +import ( + "fmt" + "os" + + "{pathToYourApp}/cmd" +) func main() { if err := cmd.RootCmd.Execute(); err != nil { @@ -313,7 +318,12 @@ In a Cobra app, typically the main.go file is very bare. It serves, one purpose, ```go package main -import "{pathToYourApp}/cmd" +import ( + "fmt" + "os" + + "{pathToYourApp}/cmd" +) func main() { if err := cmd.RootCmd.Execute(); err != nil { @@ -337,6 +347,7 @@ package cmd import ( "github.com/spf13/cobra" + "fmt" ) func init() { diff --git a/vendor/github.com/spf13/cobra/bash_completions.md b/vendor/github.com/spf13/cobra/bash_completions.md index 6e3b71f..7fa970f 100644 --- a/vendor/github.com/spf13/cobra/bash_completions.md +++ b/vendor/github.com/spf13/cobra/bash_completions.md @@ -18,7 +18,7 @@ func main() { } ``` -That will get you completions of subcommands and flags. If you make additional annotations to your code, you can get even more intelligent and flexible behavior. +`out.sh` will get you completions of subcommands and flags. Copy it to `/etc/bash_completion.d/` as described [here](https://debian-administration.org/article/316/An_introduction_to_bash_completion_part_1) and reset your terminal to use autocompletion. If you make additional annotations to your code, you can get even more intelligent and flexible behavior. ## Creating your own custom functions diff --git a/vendor/github.com/spf13/cobra/command.go b/vendor/github.com/spf13/cobra/command.go index 8f6580a..4988931 100644 --- a/vendor/github.com/spf13/cobra/command.go +++ b/vendor/github.com/spf13/cobra/command.go @@ -231,12 +231,8 @@ func (c *Command) Usage() error { // HelpFunc returns either the function set by SetHelpFunc for this command // or a parent, or it returns a function with default help behavior. func (c *Command) HelpFunc() func(*Command, []string) { - cmd := c - for cmd != nil { - if cmd.helpFunc != nil { - return cmd.helpFunc - } - cmd = cmd.parent + if helpFunc := c.checkHelpFunc(); helpFunc != nil { + return helpFunc } return func(*Command, []string) { c.mergePersistentFlags() @@ -247,6 +243,20 @@ func (c *Command) HelpFunc() func(*Command, []string) { } } +// checkHelpFunc checks if there is helpFunc in ancestors of c. +func (c *Command) checkHelpFunc() func(*Command, []string) { + if c == nil { + return nil + } + if c.helpFunc != nil { + return c.helpFunc + } + if c.HasParent() { + return c.parent.checkHelpFunc() + } + return nil +} + // Help puts out the help for the command. // Used when a user calls help [command]. // Can be defined by user by overriding HelpFunc. diff --git a/vendor/github.com/spf13/jwalterweatherman/README.md b/vendor/github.com/spf13/jwalterweatherman/README.md index c6f327c..350a968 100644 --- a/vendor/github.com/spf13/jwalterweatherman/README.md +++ b/vendor/github.com/spf13/jwalterweatherman/README.md @@ -44,7 +44,7 @@ Available Loggers are: * FATAL These each are loggers based on the log standard library and follow the -standard usage. Eg.. +standard usage. Eg. ```go import ( @@ -79,6 +79,13 @@ standard usage. Eg.. ``` +NOTE: You can also use the library in a non-global setting by creating an instance of a Notebook: + +```go +notepad = jww.NewNotepad(jww.LevelInfo, jww.LevelTrace, os.Stdout, ioutil.Discard, "", log.Ldate|log.Ltime) +notepad.WARN.Println("Some warning"") +``` + _Why 7 levels?_ Maybe you think that 7 levels are too much for any application... and you @@ -118,35 +125,15 @@ verbosity. Note that JWW's own internal output uses log levels as well, so set the log level before making any other calls if you want to see what it's up to. -### Using a temp log file - -JWW conveniently creates a temporary file and sets the log Handle to -a io.Writer created for it. You should call this early in your application -initialization routine as it will only log calls made after it is executed. -When this option is used, the library will fmt.Println where to find the -log file. - -```go - import ( - jww "github.com/spf13/jwalterweatherman" - ) - - jww.UseTempLogFile("YourAppName") - -``` ### Setting a log file -JWW can log to any file you provide a path to (provided it’s writable). -Will only append to this file. +JWW can log to any `io.Writer`: ```go - import ( - jww "github.com/spf13/jwalterweatherman" - ) - jww.SetLogFile("/path/to/logfile") + jww.SetLogOutput(customWriter) ``` diff --git a/vendor/github.com/spf13/jwalterweatherman/default_notepad.go b/vendor/github.com/spf13/jwalterweatherman/default_notepad.go new file mode 100644 index 0000000..bcb7634 --- /dev/null +++ b/vendor/github.com/spf13/jwalterweatherman/default_notepad.go @@ -0,0 +1,113 @@ +// Copyright © 2016 Steve Francia . +// +// Use of this source code is governed by an MIT-style +// license that can be found in the LICENSE file. + +package jwalterweatherman + +import ( + "io" + "io/ioutil" + "log" + "os" +) + +var ( + TRACE *log.Logger + DEBUG *log.Logger + INFO *log.Logger + WARN *log.Logger + ERROR *log.Logger + CRITICAL *log.Logger + FATAL *log.Logger + + LOG *log.Logger + FEEDBACK *Feedback + + defaultNotepad *Notepad +) + +func reloadDefaultNotepad() { + TRACE = defaultNotepad.TRACE + DEBUG = defaultNotepad.DEBUG + INFO = defaultNotepad.INFO + WARN = defaultNotepad.WARN + ERROR = defaultNotepad.ERROR + CRITICAL = defaultNotepad.CRITICAL + FATAL = defaultNotepad.FATAL + + LOG = defaultNotepad.LOG + FEEDBACK = defaultNotepad.FEEDBACK +} + +func init() { + defaultNotepad = NewNotepad(LevelError, LevelWarn, os.Stdout, ioutil.Discard, "", log.Ldate|log.Ltime) + reloadDefaultNotepad() +} + +// SetLogThreshold set the log threshold for the default notepad. Trace by default. +func SetLogThreshold(threshold Threshold) { + defaultNotepad.SetLogThreshold(threshold) + reloadDefaultNotepad() +} + +// SetLogOutput set the log output for the default notepad. Discarded by default. +func SetLogOutput(handle io.Writer) { + defaultNotepad.SetLogOutput(handle) + reloadDefaultNotepad() +} + +// SetStdoutThreshold set the standard output threshold for the default notepad. +// Info by default. +func SetStdoutThreshold(threshold Threshold) { + defaultNotepad.SetStdoutThreshold(threshold) + reloadDefaultNotepad() +} + +// SetPrefix set the prefix for the default logger. Empty by default. +func SetPrefix(prefix string) { + defaultNotepad.SetPrefix(prefix) + reloadDefaultNotepad() +} + +// SetFlags set the flags for the default logger. "log.Ldate | log.Ltime" by default. +func SetFlags(flags int) { + defaultNotepad.SetFlags(flags) + reloadDefaultNotepad() +} + +// Level returns the current global log threshold. +func LogThreshold() Threshold { + return defaultNotepad.logThreshold +} + +// Level returns the current global output threshold. +func StdoutThreshold() Threshold { + return defaultNotepad.stdoutThreshold +} + +// GetStdoutThreshold returns the defined Treshold for the log logger. +func GetLogThreshold() Threshold { + return defaultNotepad.GetLogThreshold() +} + +// GetStdoutThreshold returns the Treshold for the stdout logger. +func GetStdoutThreshold() Threshold { + return defaultNotepad.GetStdoutThreshold() +} + +// LogCountForLevel returns the number of log invocations for a given threshold. +func LogCountForLevel(l Threshold) uint64 { + return defaultNotepad.LogCountForLevel(l) +} + +// LogCountForLevelsGreaterThanorEqualTo returns the number of log invocations +// greater than or equal to a given threshold. +func LogCountForLevelsGreaterThanorEqualTo(threshold Threshold) uint64 { + return defaultNotepad.LogCountForLevelsGreaterThanorEqualTo(threshold) +} + +// ResetLogCounters resets the invocation counters for all levels. +func ResetLogCounters() { + defaultNotepad.ResetLogCounters() +} diff --git a/vendor/github.com/spf13/jwalterweatherman/log_counter.go b/vendor/github.com/spf13/jwalterweatherman/log_counter.go new file mode 100644 index 0000000..570db1d --- /dev/null +++ b/vendor/github.com/spf13/jwalterweatherman/log_counter.go @@ -0,0 +1,56 @@ +// Copyright © 2016 Steve Francia . +// +// Use of this source code is governed by an MIT-style +// license that can be found in the LICENSE file. + +package jwalterweatherman + +import ( + "sync/atomic" +) + +type logCounter struct { + counter uint64 +} + +func (c *logCounter) incr() { + atomic.AddUint64(&c.counter, 1) +} + +func (c *logCounter) resetCounter() { + atomic.StoreUint64(&c.counter, 0) +} + +func (c *logCounter) getCount() uint64 { + return atomic.LoadUint64(&c.counter) +} + +func (c *logCounter) Write(p []byte) (n int, err error) { + c.incr() + + return len(p), nil +} + +// LogCountForLevel returns the number of log invocations for a given threshold. +func (n *Notepad) LogCountForLevel(l Threshold) uint64 { + return n.logCounters[l].getCount() +} + +// LogCountForLevelsGreaterThanorEqualTo returns the number of log invocations +// greater than or equal to a given threshold. +func (n *Notepad) LogCountForLevelsGreaterThanorEqualTo(threshold Threshold) uint64 { + var cnt uint64 + + for i := int(threshold); i < len(n.logCounters); i++ { + cnt += n.LogCountForLevel(Threshold(i)) + } + + return cnt +} + +// ResetLogCounters resets the invocation counters for all levels. +func (n *Notepad) ResetLogCounters() { + for _, np := range n.logCounters { + np.resetCounter() + } +} diff --git a/vendor/github.com/spf13/jwalterweatherman/notepad.go b/vendor/github.com/spf13/jwalterweatherman/notepad.go new file mode 100644 index 0000000..5a623f4 --- /dev/null +++ b/vendor/github.com/spf13/jwalterweatherman/notepad.go @@ -0,0 +1,195 @@ +// Copyright © 2016 Steve Francia . +// +// Use of this source code is governed by an MIT-style +// license that can be found in the LICENSE file. + +package jwalterweatherman + +import ( + "fmt" + "io" + "log" + "os" +) + +type Threshold int + +func (t Threshold) String() string { + return prefixes[t] +} + +const ( + LevelTrace Threshold = iota + LevelDebug + LevelInfo + LevelWarn + LevelError + LevelCritical + LevelFatal +) + +var prefixes map[Threshold]string = map[Threshold]string{ + LevelTrace: "TRACE", + LevelDebug: "DEBUG", + LevelInfo: "INFO", + LevelWarn: "WARN", + LevelError: "ERROR", + LevelCritical: "CRITICAL", + LevelFatal: "FATAL", +} + +func prefix(t Threshold) string { + return t.String() + " " +} + +// Notepad is where you leave a note ! +type Notepad struct { + TRACE *log.Logger + DEBUG *log.Logger + INFO *log.Logger + WARN *log.Logger + ERROR *log.Logger + CRITICAL *log.Logger + FATAL *log.Logger + + LOG *log.Logger + FEEDBACK *Feedback + + loggers []**log.Logger + logHandle io.Writer + outHandle io.Writer + logThreshold Threshold + stdoutThreshold Threshold + prefix string + flags int + + // One per Threshold + logCounters [7]*logCounter +} + +// NewNotepad create a new notepad. +func NewNotepad(outThreshold Threshold, logThreshold Threshold, outHandle, logHandle io.Writer, prefix string, flags int) *Notepad { + n := &Notepad{} + + n.loggers = append(n.loggers, &n.TRACE, &n.DEBUG, &n.INFO, &n.WARN, &n.ERROR, &n.CRITICAL, &n.FATAL) + n.logHandle = logHandle + n.outHandle = outHandle + n.logThreshold = logThreshold + n.stdoutThreshold = outThreshold + + if len(prefix) != 0 { + n.prefix = "[" + prefix + "] " + } else { + n.prefix = "" + } + + n.flags = flags + + n.LOG = log.New(n.logHandle, + "LOG: ", + n.flags) + + n.FEEDBACK = &Feedback{n} + + n.init() + + return n +} + +// Feedback is special. It writes plainly to the output while +// logging with the standard extra information (date, file, etc) +// Only Println and Printf are currently provided for this +type Feedback struct { + *Notepad +} + +// init create the loggers for each level depending on the notepad thresholds +func (n *Notepad) init() { + bothHandle := io.MultiWriter(n.outHandle, n.logHandle) + + for t, logger := range n.loggers { + threshold := Threshold(t) + counter := &logCounter{} + n.logCounters[t] = counter + + switch { + case threshold >= n.logThreshold && threshold >= n.stdoutThreshold: + *logger = log.New(io.MultiWriter(counter, bothHandle), n.prefix+prefix(threshold), n.flags) + + case threshold >= n.logThreshold: + *logger = log.New(io.MultiWriter(counter, n.logHandle), n.prefix+prefix(threshold), n.flags) + + case threshold >= n.stdoutThreshold: + *logger = log.New(io.MultiWriter(counter, os.Stdout), n.prefix+prefix(threshold), n.flags) + + default: + *logger = log.New(counter, n.prefix+prefix(threshold), n.flags) + } + } +} + +// SetLogThreshold change the threshold above which messages are written to the +// log file +func (n *Notepad) SetLogThreshold(threshold Threshold) { + n.logThreshold = threshold + n.init() +} + +// SetLogOutput change the file where log messages are written +func (n *Notepad) SetLogOutput(handle io.Writer) { + n.logHandle = handle + n.init() +} + +// GetStdoutThreshold returns the defined Treshold for the log logger. +func (n *Notepad) GetLogThreshold() Threshold { + return n.logThreshold +} + +// SetStdoutThreshold change the threshold above which messages are written to the +// standard output +func (n *Notepad) SetStdoutThreshold(threshold Threshold) { + n.stdoutThreshold = threshold + n.init() +} + +// GetStdoutThreshold returns the Treshold for the stdout logger. +func (n *Notepad) GetStdoutThreshold() Threshold { + return n.stdoutThreshold +} + +// SetPrefix change the prefix used by the notepad. Prefixes are displayed between +// brackets at the begining of the line. An empty prefix won't be displayed at all. +func (n *Notepad) SetPrefix(prefix string) { + if len(prefix) != 0 { + n.prefix = "[" + prefix + "] " + } else { + n.prefix = "" + } + n.init() +} + +// SetFlags choose which flags the logger will display (after prefix and message +// level). See the package log for more informations on this. +func (n *Notepad) SetFlags(flags int) { + n.flags = flags + n.init() +} + +// Feedback is special. It writes plainly to the output while +// logging with the standard extra information (date, file, etc) +// Only Println and Printf are currently provided for this +func (fb *Feedback) Println(v ...interface{}) { + s := fmt.Sprintln(v...) + fmt.Print(s) + fb.LOG.Output(2, s) +} + +// Feedback is special. It writes plainly to the output while +// logging with the standard extra information (date, file, etc) +// Only Println and Printf are currently provided for this +func (fb *Feedback) Printf(format string, v ...interface{}) { + s := fmt.Sprintf(format, v...) + fmt.Print(s) + fb.LOG.Output(2, s) +} diff --git a/vendor/github.com/spf13/jwalterweatherman/thatswhyyoualwaysleaveanote.go b/vendor/github.com/spf13/jwalterweatherman/thatswhyyoualwaysleaveanote.go deleted file mode 100644 index b64ed46..0000000 --- a/vendor/github.com/spf13/jwalterweatherman/thatswhyyoualwaysleaveanote.go +++ /dev/null @@ -1,256 +0,0 @@ -// Copyright © 2016 Steve Francia . -// -// Use of this source code is governed by an MIT-style -// license that can be found in the LICENSE file. - -package jwalterweatherman - -import ( - "fmt" - "io" - "io/ioutil" - "log" - "os" - "sync/atomic" -) - -// Level describes the chosen log level between -// debug and critical. -type Level int - -type NotePad struct { - Handle io.Writer - Level Level - Prefix string - Logger **log.Logger - counter uint64 -} - -func (n *NotePad) incr() { - atomic.AddUint64(&n.counter, 1) -} - -func (n *NotePad) resetCounter() { - atomic.StoreUint64(&n.counter, 0) -} - -func (n *NotePad) getCount() uint64 { - return atomic.LoadUint64(&n.counter) -} - -type countingWriter struct { - incrFunc func() -} - -func (cw *countingWriter) Write(p []byte) (n int, err error) { - cw.incrFunc() - - return 0, nil -} - -// Feedback is special. It writes plainly to the output while -// logging with the standard extra information (date, file, etc) -// Only Println and Printf are currently provided for this -type Feedback struct{} - -const ( - LevelTrace Level = iota - LevelDebug - LevelInfo - LevelWarn - LevelError - LevelCritical - LevelFatal - DefaultLogThreshold = LevelWarn - DefaultStdoutThreshold = LevelError -) - -var ( - TRACE *log.Logger - DEBUG *log.Logger - INFO *log.Logger - WARN *log.Logger - ERROR *log.Logger - CRITICAL *log.Logger - FATAL *log.Logger - LOG *log.Logger - FEEDBACK Feedback - LogHandle io.Writer = ioutil.Discard - OutHandle io.Writer = os.Stdout - BothHandle io.Writer = io.MultiWriter(LogHandle, OutHandle) - NotePads []*NotePad = []*NotePad{trace, debug, info, warn, err, critical, fatal} - - trace *NotePad = &NotePad{Level: LevelTrace, Handle: os.Stdout, Logger: &TRACE, Prefix: "TRACE: "} - debug *NotePad = &NotePad{Level: LevelDebug, Handle: os.Stdout, Logger: &DEBUG, Prefix: "DEBUG: "} - info *NotePad = &NotePad{Level: LevelInfo, Handle: os.Stdout, Logger: &INFO, Prefix: "INFO: "} - warn *NotePad = &NotePad{Level: LevelWarn, Handle: os.Stdout, Logger: &WARN, Prefix: "WARN: "} - err *NotePad = &NotePad{Level: LevelError, Handle: os.Stdout, Logger: &ERROR, Prefix: "ERROR: "} - critical *NotePad = &NotePad{Level: LevelCritical, Handle: os.Stdout, Logger: &CRITICAL, Prefix: "CRITICAL: "} - fatal *NotePad = &NotePad{Level: LevelFatal, Handle: os.Stdout, Logger: &FATAL, Prefix: "FATAL: "} - logThreshold Level = DefaultLogThreshold - outputThreshold Level = DefaultStdoutThreshold -) - -const ( - DATE = log.Ldate - TIME = log.Ltime - SFILE = log.Lshortfile - LFILE = log.Llongfile - MSEC = log.Lmicroseconds -) - -var logFlags = DATE | TIME | SFILE - -func init() { - SetStdoutThreshold(DefaultStdoutThreshold) -} - -// initialize will setup the jWalterWeatherman standard approach of providing the user -// some feedback and logging a potentially different amount based on independent log and output thresholds. -// By default the output has a lower threshold than logged -// Don't use if you have manually set the Handles of the different levels as it will overwrite them. -func initialize() { - BothHandle = io.MultiWriter(LogHandle, OutHandle) - - for _, n := range NotePads { - if n.Level < outputThreshold && n.Level < logThreshold { - n.Handle = ioutil.Discard - } else if n.Level >= outputThreshold && n.Level >= logThreshold { - n.Handle = BothHandle - } else if n.Level >= outputThreshold && n.Level < logThreshold { - n.Handle = OutHandle - } else { - n.Handle = LogHandle - } - } - - for _, n := range NotePads { - n.Handle = io.MultiWriter(n.Handle, &countingWriter{n.incr}) - *n.Logger = log.New(n.Handle, n.Prefix, logFlags) - } - - LOG = log.New(LogHandle, - "LOG: ", - logFlags) -} - -// Set the log Flags (Available flag: DATE, TIME, SFILE, LFILE and MSEC) -func SetLogFlag(flags int) { - logFlags = flags - initialize() -} - -// Level returns the current global log threshold. -func LogThreshold() Level { - return logThreshold -} - -// Level returns the current global output threshold. -func StdoutThreshold() Level { - return outputThreshold -} - -// Ensures that the level provided is within the bounds of available levels -func levelCheck(level Level) Level { - switch { - case level <= LevelTrace: - return LevelTrace - case level >= LevelFatal: - return LevelFatal - default: - return level - } -} - -// Establishes a threshold where anything matching or above will be logged -func SetLogThreshold(level Level) { - logThreshold = levelCheck(level) - initialize() -} - -// Establishes a threshold where anything matching or above will be output -func SetStdoutThreshold(level Level) { - outputThreshold = levelCheck(level) - initialize() -} - -// Conveniently Sets the Log Handle to a io.writer created for the file behind the given filepath -// Will only append to this file -func SetLogFile(path string) { - file, err := os.OpenFile(path, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0666) - if err != nil { - CRITICAL.Println("Failed to open log file:", path, err) - os.Exit(-1) - } - - INFO.Println("Logging to", file.Name()) - - LogHandle = file - initialize() -} - -// Conveniently Creates a temporary file and sets the Log Handle to a io.writer created for it -func UseTempLogFile(prefix string) { - file, err := ioutil.TempFile(os.TempDir(), prefix) - if err != nil { - CRITICAL.Println(err) - } - - INFO.Println("Logging to", file.Name()) - - LogHandle = file - initialize() -} - -// LogCountForLevel returns the number of log invocations for a given level. -func LogCountForLevel(l Level) uint64 { - for _, np := range NotePads { - if np.Level == l { - return np.getCount() - } - } - return 0 -} - -// LogCountForLevelsGreaterThanorEqualTo returns the number of log invocations -// greater than or equal to a given level threshold. -func LogCountForLevelsGreaterThanorEqualTo(threshold Level) uint64 { - var cnt uint64 - for _, np := range NotePads { - if np.Level >= threshold { - cnt += np.getCount() - } - } - return cnt -} - -// ResetLogCounters resets the invocation counters for all levels. -func ResetLogCounters() { - for _, np := range NotePads { - np.resetCounter() - } -} - -// Disables logging for the entire JWW system -func DiscardLogging() { - LogHandle = ioutil.Discard - initialize() -} - -// Feedback is special. It writes plainly to the output while -// logging with the standard extra information (date, file, etc) -// Only Println and Printf are currently provided for this -func (fb *Feedback) Println(v ...interface{}) { - s := fmt.Sprintln(v...) - fmt.Print(s) - LOG.Output(2, s) -} - -// Feedback is special. It writes plainly to the output while -// logging with the standard extra information (date, file, etc) -// Only Println and Printf are currently provided for this -func (fb *Feedback) Printf(format string, v ...interface{}) { - s := fmt.Sprintf(format, v...) - fmt.Print(s) - LOG.Output(2, s) -} diff --git a/vendor/github.com/spf13/pflag/README.md b/vendor/github.com/spf13/pflag/README.md index 08ad945..eefb46d 100644 --- a/vendor/github.com/spf13/pflag/README.md +++ b/vendor/github.com/spf13/pflag/README.md @@ -1,4 +1,6 @@ [![Build Status](https://travis-ci.org/spf13/pflag.svg?branch=master)](https://travis-ci.org/spf13/pflag) +[![Go Report Card](https://goreportcard.com/badge/github.com/spf13/pflag)](https://goreportcard.com/report/github.com/spf13/pflag) +[![GoDoc](https://godoc.org/github.com/spf13/pflag?status.svg)](https://godoc.org/github.com/spf13/pflag) ## Description @@ -106,9 +108,9 @@ that give one-letter shorthands for flags. You can use these by appending var ip = flag.IntP("flagname", "f", 1234, "help message") var flagvar bool func init() { - flag.BoolVarP("boolname", "b", true, "help message") + flag.BoolVarP(&flagvar, "boolname", "b", true, "help message") } -flag.VarP(&flagVar, "varname", "v", 1234, "help message") +flag.VarP(&flagVal, "varname", "v", "help message") ``` Shorthand letters can be used with single dashes on the command line. diff --git a/vendor/github.com/spf13/pflag/flag.go b/vendor/github.com/spf13/pflag/flag.go index 4258f45..b4bfecb 100644 --- a/vendor/github.com/spf13/pflag/flag.go +++ b/vendor/github.com/spf13/pflag/flag.go @@ -514,7 +514,7 @@ func (f *FlagSet) FlagUsages() string { if len(flag.NoOptDefVal) > 0 { switch flag.Value.Type() { case "string": - line += fmt.Sprintf("[=%q]", flag.NoOptDefVal) + line += fmt.Sprintf("[=\"%s\"]", flag.NoOptDefVal) case "bool": if flag.NoOptDefVal != "true" { line += fmt.Sprintf("[=%s]", flag.NoOptDefVal) @@ -534,7 +534,7 @@ func (f *FlagSet) FlagUsages() string { line += usage if !flag.defaultIsZeroValue() { if flag.Value.Type() == "string" { - line += fmt.Sprintf(" (default %q)", flag.DefValue) + line += fmt.Sprintf(" (default \"%s\")", flag.DefValue) } else { line += fmt.Sprintf(" (default %s)", flag.DefValue) } @@ -752,7 +752,7 @@ func containsShorthand(arg, shorthand string) bool { return strings.Contains(arg, shorthand) } -func (f *FlagSet) parseLongArg(s string, args []string) (a []string, err error) { +func (f *FlagSet) parseLongArg(s string, args []string, fn parseFunc) (a []string, err error) { a = args name := s[2:] if len(name) == 0 || name[0] == '-' || name[0] == '=' { @@ -786,11 +786,11 @@ func (f *FlagSet) parseLongArg(s string, args []string) (a []string, err error) err = f.failf("flag needs an argument: %s", s) return } - err = f.setFlag(flag, value, s) + err = fn(flag, value, s) return } -func (f *FlagSet) parseSingleShortArg(shorthands string, args []string) (outShorts string, outArgs []string, err error) { +func (f *FlagSet) parseSingleShortArg(shorthands string, args []string, fn parseFunc) (outShorts string, outArgs []string, err error) { if strings.HasPrefix(shorthands, "test.") { return } @@ -825,16 +825,16 @@ func (f *FlagSet) parseSingleShortArg(shorthands string, args []string) (outShor err = f.failf("flag needs an argument: %q in -%s", c, shorthands) return } - err = f.setFlag(flag, value, shorthands) + err = fn(flag, value, shorthands) return } -func (f *FlagSet) parseShortArg(s string, args []string) (a []string, err error) { +func (f *FlagSet) parseShortArg(s string, args []string, fn parseFunc) (a []string, err error) { a = args shorthands := s[1:] for len(shorthands) > 0 { - shorthands, a, err = f.parseSingleShortArg(shorthands, args) + shorthands, a, err = f.parseSingleShortArg(shorthands, args, fn) if err != nil { return } @@ -843,7 +843,7 @@ func (f *FlagSet) parseShortArg(s string, args []string) (a []string, err error) return } -func (f *FlagSet) parseArgs(args []string) (err error) { +func (f *FlagSet) parseArgs(args []string, fn parseFunc) (err error) { for len(args) > 0 { s := args[0] args = args[1:] @@ -863,9 +863,9 @@ func (f *FlagSet) parseArgs(args []string) (err error) { f.args = append(f.args, args...) break } - args, err = f.parseLongArg(s, args) + args, err = f.parseLongArg(s, args, fn) } else { - args, err = f.parseShortArg(s, args) + args, err = f.parseShortArg(s, args, fn) } if err != nil { return @@ -881,7 +881,41 @@ func (f *FlagSet) parseArgs(args []string) (err error) { func (f *FlagSet) Parse(arguments []string) error { f.parsed = true f.args = make([]string, 0, len(arguments)) - err := f.parseArgs(arguments) + + assign := func(flag *Flag, value, origArg string) error { + return f.setFlag(flag, value, origArg) + } + + err := f.parseArgs(arguments, assign) + if err != nil { + switch f.errorHandling { + case ContinueOnError: + return err + case ExitOnError: + os.Exit(2) + case PanicOnError: + panic(err) + } + } + return nil +} + +type parseFunc func(flag *Flag, value, origArg string) error + +// ParseAll parses flag definitions from the argument list, which should not +// include the command name. The arguments for fn are flag and value. Must be +// called after all flags in the FlagSet are defined and before flags are +// accessed by the program. The return value will be ErrHelp if -help was set +// but not defined. +func (f *FlagSet) ParseAll(arguments []string, fn func(flag *Flag, value string) error) error { + f.parsed = true + f.args = make([]string, 0, len(arguments)) + + assign := func(flag *Flag, value, origArg string) error { + return fn(flag, value) + } + + err := f.parseArgs(arguments, assign) if err != nil { switch f.errorHandling { case ContinueOnError: @@ -907,6 +941,14 @@ func Parse() { CommandLine.Parse(os.Args[1:]) } +// ParseAll parses the command-line flags from os.Args[1:] and called fn for each. +// The arguments for fn are flag and value. Must be called after all flags are +// defined and before flags are accessed by the program. +func ParseAll(fn func(flag *Flag, value string) error) { + // Ignore errors; CommandLine is set for ExitOnError. + CommandLine.ParseAll(os.Args[1:], fn) +} + // SetInterspersed sets whether to support interspersed option/non-option arguments. func SetInterspersed(interspersed bool) { CommandLine.SetInterspersed(interspersed) diff --git a/vendor/github.com/spf13/viper/util.go b/vendor/github.com/spf13/viper/util.go index b0903fb..3ebada9 100644 --- a/vendor/github.com/spf13/viper/util.go +++ b/vendor/github.com/spf13/viper/util.go @@ -39,17 +39,58 @@ func (pe ConfigParseError) Error() string { return fmt.Sprintf("While parsing config: %s", pe.err.Error()) } +// toCaseInsensitiveValue checks if the value is a map; +// if so, create a copy and lower-case the keys recursively. +func toCaseInsensitiveValue(value interface{}) interface{} { + switch v := value.(type) { + case map[interface{}]interface{}: + value = copyAndInsensitiviseMap(cast.ToStringMap(v)) + case map[string]interface{}: + value = copyAndInsensitiviseMap(v) + } + + return value +} + +// copyAndInsensitiviseMap behaves like insensitiviseMap, but creates a copy of +// any map it makes case insensitive. +func copyAndInsensitiviseMap(m map[string]interface{}) map[string]interface{} { + nm := make(map[string]interface{}) + + for key, val := range m { + lkey := strings.ToLower(key) + switch v := val.(type) { + case map[interface{}]interface{}: + nm[lkey] = copyAndInsensitiviseMap(cast.ToStringMap(v)) + case map[string]interface{}: + nm[lkey] = copyAndInsensitiviseMap(v) + default: + nm[lkey] = v + } + } + + return nm +} + func insensitiviseMap(m map[string]interface{}) { for key, val := range m { + switch val.(type) { + case map[interface{}]interface{}: + // nested map: cast and recursively insensitivise + val = cast.ToStringMap(val) + insensitiviseMap(val.(map[string]interface{})) + case map[string]interface{}: + // nested map: recursively insensitivise + insensitiviseMap(val.(map[string]interface{})) + } + lower := strings.ToLower(key) if key != lower { + // remove old key (not lower-cased) delete(m, key) - m[lower] = val - if m2, ok := val.(map[string]interface{}); ok { - // nested map: recursively insensitivise - insensitiviseMap(m2) - } } + // update map + m[lower] = val } } diff --git a/vendor/github.com/spf13/viper/viper.go b/vendor/github.com/spf13/viper/viper.go index a03540c..2603c78 100644 --- a/vendor/github.com/spf13/viper/viper.go +++ b/vendor/github.com/spf13/viper/viper.go @@ -241,7 +241,13 @@ func (v *Viper) WatchConfig() { defer watcher.Close() // we have to watch the entire directory to pick up renames/atomic saves in a cross-platform way - configFile := filepath.Clean(v.getConfigFile()) + filename, err := v.getConfigFile() + if err != nil { + log.Println("error:", err) + return + } + + configFile := filepath.Clean(filename) configDir, _ := filepath.Split(configFile) done := make(chan bool) @@ -399,49 +405,22 @@ func (v *Viper) providerPathExists(p *defaultRemoteProvider) bool { return false } -// searchMapForKey may end up traversing the map if the key references a nested -// item (foo.bar), but will use a fast path for the common case. -// Note: This assumes that the key given is already lowercase. -func (v *Viper) searchMapForKey(source map[string]interface{}, lcaseKey string) interface{} { - if !strings.Contains(lcaseKey, v.keyDelim) { - v, ok := source[lcaseKey] - if ok { - return v - } - return nil - } - - path := strings.Split(lcaseKey, v.keyDelim) - return v.searchMap(source, path) -} - // searchMap recursively searches for a value for path in source map. // Returns nil if not found. -// Note: This assumes that the path entries are lower cased. +// Note: This assumes that the path entries and map keys are lower cased. func (v *Viper) searchMap(source map[string]interface{}, path []string) interface{} { if len(path) == 0 { return source } - // Fast path - if len(path) == 1 { - if v, ok := source[path[0]]; ok { - return v + next, ok := source[path[0]] + if ok { + // Fast path + if len(path) == 1 { + return next } - return nil - } - var ok bool - var next interface{} - for k, v := range source { - if k == path[0] { - ok = true - next = v - break - } - } - - if ok { + // Nested case switch next.(type) { case map[interface{}]interface{}: return v.searchMap(cast.ToStringMap(next), path[1:]) @@ -450,9 +429,6 @@ func (v *Viper) searchMap(source map[string]interface{}, path []string) interfac // if the type of `next` is the same as the type being asserted return v.searchMap(next.(map[string]interface{}), path[1:]) default: - if len(path) == 1 { - return next - } // got a value but nested key expected, return "nil" for not found return nil } @@ -469,6 +445,8 @@ func (v *Viper) searchMap(source map[string]interface{}, path []string) interfac // // This should be useful only at config level (other maps may not contain dots // in their keys). +// +// Note: This assumes that the path entries and map keys are lower cased. func (v *Viper) searchMapWithPathPrefixes(source map[string]interface{}, path []string) interface{} { if len(path) == 0 { return source @@ -478,17 +456,14 @@ func (v *Viper) searchMapWithPathPrefixes(source map[string]interface{}, path [] for i := len(path); i > 0; i-- { prefixKey := strings.ToLower(strings.Join(path[0:i], v.keyDelim)) - var ok bool - var next interface{} - for k, v := range source { - if strings.ToLower(k) == prefixKey { - ok = true - next = v - break + next, ok := source[prefixKey] + if ok { + // Fast path + if i == len(path) { + return next } - } - if ok { + // Nested case var val interface{} switch next.(type) { case map[interface{}]interface{}: @@ -498,9 +473,6 @@ func (v *Viper) searchMapWithPathPrefixes(source map[string]interface{}, path [] // if the type of `next` is the same as the type being asserted val = v.searchMapWithPathPrefixes(next.(map[string]interface{}), path[i:]) default: - if len(path) == i { - val = next - } // got a value but nested key expected, do nothing and look for next prefix } if val != nil { @@ -604,6 +576,7 @@ func GetViper() *Viper { } // Get can retrieve any value given the key to use. +// Get is case-insensitive for a key. // Get has the behavior of returning the value associated with the first // place from where it is set. Viper will check in the following order: // override, flag, env, config file, key/value store, default @@ -620,7 +593,8 @@ func (v *Viper) Get(key string) interface{} { valType := val if v.typeByDefValue { // TODO(bep) this branch isn't covered by a single test. - defVal := v.searchMapForKey(v.defaults, lcaseKey) + path := strings.Split(lcaseKey, v.keyDelim) + defVal := v.searchMap(v.defaults, path) if defVal != nil { valType = defVal } @@ -646,6 +620,7 @@ func (v *Viper) Get(key string) interface{} { } // Sub returns new Viper instance representing a sub tree of this instance. +// Sub is case-insensitive for a key. func Sub(key string) *Viper { return v.Sub(key) } func (v *Viper) Sub(key string) *Viper { subv := New() @@ -883,16 +858,14 @@ func (v *Viper) find(lcaseKey string) interface{} { // if the requested key is an alias, then return the proper key lcaseKey = v.realKey(lcaseKey) + path = strings.Split(lcaseKey, v.keyDelim) + nested = len(path) > 1 // Set() override first - val = v.searchMapForKey(v.override, lcaseKey) + val = v.searchMap(v.override, path) if val != nil { return val } - - path = strings.Split(lcaseKey, v.keyDelim) - nested = len(path) > 1 - if nested && v.isPathShadowedInDeepMap(path, v.override) != "" { return nil } @@ -912,7 +885,6 @@ func (v *Viper) find(lcaseKey string) interface{} { return flag.ValueString() } } - if nested && v.isPathShadowedInFlatMap(path, v.pflags) != "" { return nil } @@ -934,7 +906,7 @@ func (v *Viper) find(lcaseKey string) interface{} { return val } } - if shadow := v.isPathShadowedInFlatMap(path, v.env); shadow != "" { + if nested && v.isPathShadowedInFlatMap(path, v.env) != "" { return nil } @@ -943,7 +915,7 @@ func (v *Viper) find(lcaseKey string) interface{} { if val != nil { return val } - if shadow := v.isPathShadowedInDeepMap(path, v.config); shadow != "" { + if nested && v.isPathShadowedInDeepMap(path, v.config) != "" { return nil } @@ -952,7 +924,7 @@ func (v *Viper) find(lcaseKey string) interface{} { if val != nil { return val } - if shadow := v.isPathShadowedInDeepMap(path, v.kvstore); shadow != "" { + if nested && v.isPathShadowedInDeepMap(path, v.kvstore) != "" { return nil } @@ -961,7 +933,7 @@ func (v *Viper) find(lcaseKey string) interface{} { if val != nil { return val } - if shadow := v.isPathShadowedInDeepMap(path, v.defaults); shadow != "" { + if nested && v.isPathShadowedInDeepMap(path, v.defaults) != "" { return nil } @@ -986,6 +958,7 @@ func (v *Viper) find(lcaseKey string) interface{} { } // IsSet checks to see if the key has been set in any of the data locations. +// IsSet is case-insensitive for a key. func IsSet(key string) bool { return v.IsSet(key) } func (v *Viper) IsSet(key string) bool { lcaseKey := strings.ToLower(key) @@ -1067,11 +1040,13 @@ func (v *Viper) InConfig(key string) bool { } // SetDefault sets the default value for this key. +// SetDefault is case-insensitive for a key. // Default only used when no value is provided by the user via flag, config or ENV. func SetDefault(key string, value interface{}) { v.SetDefault(key, value) } func (v *Viper) SetDefault(key string, value interface{}) { // If alias passed in, then set the proper default key = v.realKey(strings.ToLower(key)) + value = toCaseInsensitiveValue(value) path := strings.Split(key, v.keyDelim) lastKey := strings.ToLower(path[len(path)-1]) @@ -1082,12 +1057,14 @@ func (v *Viper) SetDefault(key string, value interface{}) { } // Set sets the value for the key in the override regiser. +// Set is case-insensitive for a key. // Will be used instead of values obtained via // flags, config file, ENV, default, or key/value store. func Set(key string, value interface{}) { v.Set(key, value) } func (v *Viper) Set(key string, value interface{}) { // If alias passed in, then set the proper override key = v.realKey(strings.ToLower(key)) + value = toCaseInsensitiveValue(value) path := strings.Split(key, v.keyDelim) lastKey := strings.ToLower(path[len(path)-1]) @@ -1102,11 +1079,16 @@ func (v *Viper) Set(key string, value interface{}) { func ReadInConfig() error { return v.ReadInConfig() } func (v *Viper) ReadInConfig() error { jww.INFO.Println("Attempting to read in config file") + filename, err := v.getConfigFile() + if err != nil { + return err + } + if !stringInSlice(v.getConfigType(), SupportedExts) { return UnsupportedConfigError(v.getConfigType()) } - file, err := afero.ReadFile(v.fs, v.getConfigFile()) + file, err := afero.ReadFile(v.fs, filename) if err != nil { return err } @@ -1120,11 +1102,16 @@ func (v *Viper) ReadInConfig() error { func MergeInConfig() error { return v.MergeInConfig() } func (v *Viper) MergeInConfig() error { jww.INFO.Println("Attempting to merge in config file") + filename, err := v.getConfigFile() + if err != nil { + return err + } + if !stringInSlice(v.getConfigType(), SupportedExts) { return UnsupportedConfigError(v.getConfigType()) } - file, err := afero.ReadFile(v.fs, v.getConfigFile()) + file, err := afero.ReadFile(v.fs, filename) if err != nil { return err } @@ -1182,6 +1169,14 @@ func castMapStringToMapInterface(src map[string]string) map[string]interface{} { return tgt } +func castMapFlagToMapInterface(src map[string]FlagValue) map[string]interface{} { + tgt := map[string]interface{}{} + for k, v := range src { + tgt[k] = v + } + return tgt +} + // mergeMaps merges two maps. The `itgt` parameter is for handling go-yaml's // insistence on parsing nested structures as `map[interface{}]interface{}` // instead of using a `string` as the key for nest structures beyond one level @@ -1327,8 +1322,8 @@ func (v *Viper) AllKeys() []string { // add all paths, by order of descending priority to ensure correct shadowing m = v.flattenAndMergeMap(m, castMapStringToMapInterface(v.aliases), "") m = v.flattenAndMergeMap(m, v.override, "") - m = v.mergeFlatMap(m, v.pflags) - m = v.mergeFlatMap(m, v.env) + m = v.mergeFlatMap(m, castMapFlagToMapInterface(v.pflags)) + m = v.mergeFlatMap(m, castMapStringToMapInterface(v.env)) m = v.flattenAndMergeMap(m, v.config, "") m = v.flattenAndMergeMap(m, v.kvstore, "") m = v.flattenAndMergeMap(m, v.defaults, "") @@ -1380,16 +1375,7 @@ func (v *Viper) flattenAndMergeMap(shadow map[string]bool, m map[string]interfac // mergeFlatMap merges the given maps, excluding values of the second map // shadowed by values from the first map. -func (v *Viper) mergeFlatMap(shadow map[string]bool, mi interface{}) map[string]bool { - // unify input map - var m map[string]interface{} - switch mi.(type) { - case map[string]string, map[string]FlagValue: - m = cast.ToStringMap(mi) - default: - return shadow - } - +func (v *Viper) mergeFlatMap(shadow map[string]bool, m map[string]interface{}) map[string]bool { // scan keys outer: for k, _ := range m { @@ -1460,7 +1446,11 @@ func (v *Viper) getConfigType() string { return v.configType } - cf := v.getConfigFile() + cf, err := v.getConfigFile() + if err != nil { + return "" + } + ext := filepath.Ext(cf) if len(ext) > 1 { @@ -1470,15 +1460,15 @@ func (v *Viper) getConfigType() string { return "" } -func (v *Viper) getConfigFile() string { +func (v *Viper) getConfigFile() (string, error) { // if explicitly set, then use it if v.configFile != "" { - return v.configFile + return v.configFile, nil } cf, err := v.findConfigFile() if err != nil { - return "" + return "", err } v.configFile = cf diff --git a/vendor/github.com/stretchr/testify/LICENSE b/vendor/github.com/stretchr/testify/LICENSE deleted file mode 100644 index 473b670..0000000 --- a/vendor/github.com/stretchr/testify/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -Copyright (c) 2012 - 2013 Mat Ryer and Tyler Bunnell - -Please consider promoting this project if you find it useful. - -Permission is hereby granted, free of charge, to any person -obtaining a copy of this software and associated documentation -files (the "Software"), to deal in the Software without restriction, -including without limitation the rights to use, copy, modify, merge, -publish, distribute, sublicense, and/or sell copies of the Software, -and to permit persons to whom the Software is furnished to do so, -subject to the following conditions: - -The above copyright notice and this permission notice shall be included -in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT -OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE -OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/github.com/stretchr/testify/assert/assertion_forward.go b/vendor/github.com/stretchr/testify/assert/assertion_forward.go deleted file mode 100644 index e6a7960..0000000 --- a/vendor/github.com/stretchr/testify/assert/assertion_forward.go +++ /dev/null @@ -1,387 +0,0 @@ -/* -* CODE GENERATED AUTOMATICALLY WITH github.com/stretchr/testify/_codegen -* THIS FILE MUST NOT BE EDITED BY HAND -*/ - -package assert - -import ( - - http "net/http" - url "net/url" - time "time" -) - - -// Condition uses a Comparison to assert a complex condition. -func (a *Assertions) Condition(comp Comparison, msgAndArgs ...interface{}) bool { - return Condition(a.t, comp, msgAndArgs...) -} - - -// Contains asserts that the specified string, list(array, slice...) or map contains the -// specified substring or element. -// -// a.Contains("Hello World", "World", "But 'Hello World' does contain 'World'") -// a.Contains(["Hello", "World"], "World", "But ["Hello", "World"] does contain 'World'") -// a.Contains({"Hello": "World"}, "Hello", "But {'Hello': 'World'} does contain 'Hello'") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) Contains(s interface{}, contains interface{}, msgAndArgs ...interface{}) bool { - return Contains(a.t, s, contains, msgAndArgs...) -} - - -// Empty asserts that the specified object is empty. I.e. nil, "", false, 0 or either -// a slice or a channel with len == 0. -// -// a.Empty(obj) -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) Empty(object interface{}, msgAndArgs ...interface{}) bool { - return Empty(a.t, object, msgAndArgs...) -} - - -// Equal asserts that two objects are equal. -// -// a.Equal(123, 123, "123 and 123 should be equal") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) Equal(expected interface{}, actual interface{}, msgAndArgs ...interface{}) bool { - return Equal(a.t, expected, actual, msgAndArgs...) -} - - -// EqualError asserts that a function returned an error (i.e. not `nil`) -// and that it is equal to the provided error. -// -// actualObj, err := SomeFunction() -// if assert.Error(t, err, "An error was expected") { -// assert.Equal(t, err, expectedError) -// } -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) EqualError(theError error, errString string, msgAndArgs ...interface{}) bool { - return EqualError(a.t, theError, errString, msgAndArgs...) -} - - -// EqualValues asserts that two objects are equal or convertable to the same types -// and equal. -// -// a.EqualValues(uint32(123), int32(123), "123 and 123 should be equal") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) EqualValues(expected interface{}, actual interface{}, msgAndArgs ...interface{}) bool { - return EqualValues(a.t, expected, actual, msgAndArgs...) -} - - -// Error asserts that a function returned an error (i.e. not `nil`). -// -// actualObj, err := SomeFunction() -// if a.Error(err, "An error was expected") { -// assert.Equal(t, err, expectedError) -// } -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) Error(err error, msgAndArgs ...interface{}) bool { - return Error(a.t, err, msgAndArgs...) -} - - -// Exactly asserts that two objects are equal is value and type. -// -// a.Exactly(int32(123), int64(123), "123 and 123 should NOT be equal") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) Exactly(expected interface{}, actual interface{}, msgAndArgs ...interface{}) bool { - return Exactly(a.t, expected, actual, msgAndArgs...) -} - - -// Fail reports a failure through -func (a *Assertions) Fail(failureMessage string, msgAndArgs ...interface{}) bool { - return Fail(a.t, failureMessage, msgAndArgs...) -} - - -// FailNow fails test -func (a *Assertions) FailNow(failureMessage string, msgAndArgs ...interface{}) bool { - return FailNow(a.t, failureMessage, msgAndArgs...) -} - - -// False asserts that the specified value is false. -// -// a.False(myBool, "myBool should be false") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) False(value bool, msgAndArgs ...interface{}) bool { - return False(a.t, value, msgAndArgs...) -} - - -// HTTPBodyContains asserts that a specified handler returns a -// body that contains a string. -// -// a.HTTPBodyContains(myHandler, "www.google.com", nil, "I'm Feeling Lucky") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) HTTPBodyContains(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}) bool { - return HTTPBodyContains(a.t, handler, method, url, values, str) -} - - -// HTTPBodyNotContains asserts that a specified handler returns a -// body that does not contain a string. -// -// a.HTTPBodyNotContains(myHandler, "www.google.com", nil, "I'm Feeling Lucky") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) HTTPBodyNotContains(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}) bool { - return HTTPBodyNotContains(a.t, handler, method, url, values, str) -} - - -// HTTPError asserts that a specified handler returns an error status code. -// -// a.HTTPError(myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) HTTPError(handler http.HandlerFunc, method string, url string, values url.Values) bool { - return HTTPError(a.t, handler, method, url, values) -} - - -// HTTPRedirect asserts that a specified handler returns a redirect status code. -// -// a.HTTPRedirect(myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) HTTPRedirect(handler http.HandlerFunc, method string, url string, values url.Values) bool { - return HTTPRedirect(a.t, handler, method, url, values) -} - - -// HTTPSuccess asserts that a specified handler returns a success status code. -// -// a.HTTPSuccess(myHandler, "POST", "http://www.google.com", nil) -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) HTTPSuccess(handler http.HandlerFunc, method string, url string, values url.Values) bool { - return HTTPSuccess(a.t, handler, method, url, values) -} - - -// Implements asserts that an object is implemented by the specified interface. -// -// a.Implements((*MyInterface)(nil), new(MyObject), "MyObject") -func (a *Assertions) Implements(interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) bool { - return Implements(a.t, interfaceObject, object, msgAndArgs...) -} - - -// InDelta asserts that the two numerals are within delta of each other. -// -// a.InDelta(math.Pi, (22 / 7.0), 0.01) -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) InDelta(expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) bool { - return InDelta(a.t, expected, actual, delta, msgAndArgs...) -} - - -// InDeltaSlice is the same as InDelta, except it compares two slices. -func (a *Assertions) InDeltaSlice(expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) bool { - return InDeltaSlice(a.t, expected, actual, delta, msgAndArgs...) -} - - -// InEpsilon asserts that expected and actual have a relative error less than epsilon -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) InEpsilon(expected interface{}, actual interface{}, epsilon float64, msgAndArgs ...interface{}) bool { - return InEpsilon(a.t, expected, actual, epsilon, msgAndArgs...) -} - - -// InEpsilonSlice is the same as InEpsilon, except it compares two slices. -func (a *Assertions) InEpsilonSlice(expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) bool { - return InEpsilonSlice(a.t, expected, actual, delta, msgAndArgs...) -} - - -// IsType asserts that the specified objects are of the same type. -func (a *Assertions) IsType(expectedType interface{}, object interface{}, msgAndArgs ...interface{}) bool { - return IsType(a.t, expectedType, object, msgAndArgs...) -} - - -// JSONEq asserts that two JSON strings are equivalent. -// -// a.JSONEq(`{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`) -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) JSONEq(expected string, actual string, msgAndArgs ...interface{}) bool { - return JSONEq(a.t, expected, actual, msgAndArgs...) -} - - -// Len asserts that the specified object has specific length. -// Len also fails if the object has a type that len() not accept. -// -// a.Len(mySlice, 3, "The size of slice is not 3") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) Len(object interface{}, length int, msgAndArgs ...interface{}) bool { - return Len(a.t, object, length, msgAndArgs...) -} - - -// Nil asserts that the specified object is nil. -// -// a.Nil(err, "err should be nothing") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) Nil(object interface{}, msgAndArgs ...interface{}) bool { - return Nil(a.t, object, msgAndArgs...) -} - - -// NoError asserts that a function returned no error (i.e. `nil`). -// -// actualObj, err := SomeFunction() -// if a.NoError(err) { -// assert.Equal(t, actualObj, expectedObj) -// } -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) NoError(err error, msgAndArgs ...interface{}) bool { - return NoError(a.t, err, msgAndArgs...) -} - - -// NotContains asserts that the specified string, list(array, slice...) or map does NOT contain the -// specified substring or element. -// -// a.NotContains("Hello World", "Earth", "But 'Hello World' does NOT contain 'Earth'") -// a.NotContains(["Hello", "World"], "Earth", "But ['Hello', 'World'] does NOT contain 'Earth'") -// a.NotContains({"Hello": "World"}, "Earth", "But {'Hello': 'World'} does NOT contain 'Earth'") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) NotContains(s interface{}, contains interface{}, msgAndArgs ...interface{}) bool { - return NotContains(a.t, s, contains, msgAndArgs...) -} - - -// NotEmpty asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either -// a slice or a channel with len == 0. -// -// if a.NotEmpty(obj) { -// assert.Equal(t, "two", obj[1]) -// } -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) NotEmpty(object interface{}, msgAndArgs ...interface{}) bool { - return NotEmpty(a.t, object, msgAndArgs...) -} - - -// NotEqual asserts that the specified values are NOT equal. -// -// a.NotEqual(obj1, obj2, "two objects shouldn't be equal") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) NotEqual(expected interface{}, actual interface{}, msgAndArgs ...interface{}) bool { - return NotEqual(a.t, expected, actual, msgAndArgs...) -} - - -// NotNil asserts that the specified object is not nil. -// -// a.NotNil(err, "err should be something") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) NotNil(object interface{}, msgAndArgs ...interface{}) bool { - return NotNil(a.t, object, msgAndArgs...) -} - - -// NotPanics asserts that the code inside the specified PanicTestFunc does NOT panic. -// -// a.NotPanics(func(){ -// RemainCalm() -// }, "Calling RemainCalm() should NOT panic") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) NotPanics(f PanicTestFunc, msgAndArgs ...interface{}) bool { - return NotPanics(a.t, f, msgAndArgs...) -} - - -// NotRegexp asserts that a specified regexp does not match a string. -// -// a.NotRegexp(regexp.MustCompile("starts"), "it's starting") -// a.NotRegexp("^start", "it's not starting") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) NotRegexp(rx interface{}, str interface{}, msgAndArgs ...interface{}) bool { - return NotRegexp(a.t, rx, str, msgAndArgs...) -} - - -// NotZero asserts that i is not the zero value for its type and returns the truth. -func (a *Assertions) NotZero(i interface{}, msgAndArgs ...interface{}) bool { - return NotZero(a.t, i, msgAndArgs...) -} - - -// Panics asserts that the code inside the specified PanicTestFunc panics. -// -// a.Panics(func(){ -// GoCrazy() -// }, "Calling GoCrazy() should panic") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) Panics(f PanicTestFunc, msgAndArgs ...interface{}) bool { - return Panics(a.t, f, msgAndArgs...) -} - - -// Regexp asserts that a specified regexp matches a string. -// -// a.Regexp(regexp.MustCompile("start"), "it's starting") -// a.Regexp("start...$", "it's not starting") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) Regexp(rx interface{}, str interface{}, msgAndArgs ...interface{}) bool { - return Regexp(a.t, rx, str, msgAndArgs...) -} - - -// True asserts that the specified value is true. -// -// a.True(myBool, "myBool should be true") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) True(value bool, msgAndArgs ...interface{}) bool { - return True(a.t, value, msgAndArgs...) -} - - -// WithinDuration asserts that the two times are within duration delta of each other. -// -// a.WithinDuration(time.Now(), time.Now(), 10*time.Second, "The difference should not be more than 10s") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) WithinDuration(expected time.Time, actual time.Time, delta time.Duration, msgAndArgs ...interface{}) bool { - return WithinDuration(a.t, expected, actual, delta, msgAndArgs...) -} - - -// Zero asserts that i is the zero value for its type and returns the truth. -func (a *Assertions) Zero(i interface{}, msgAndArgs ...interface{}) bool { - return Zero(a.t, i, msgAndArgs...) -} diff --git a/vendor/github.com/stretchr/testify/assert/assertion_forward.go.tmpl b/vendor/github.com/stretchr/testify/assert/assertion_forward.go.tmpl deleted file mode 100644 index 99f9acf..0000000 --- a/vendor/github.com/stretchr/testify/assert/assertion_forward.go.tmpl +++ /dev/null @@ -1,4 +0,0 @@ -{{.CommentWithoutT "a"}} -func (a *Assertions) {{.DocInfo.Name}}({{.Params}}) bool { - return {{.DocInfo.Name}}(a.t, {{.ForwardedParams}}) -} diff --git a/vendor/github.com/stretchr/testify/assert/assertions.go b/vendor/github.com/stretchr/testify/assert/assertions.go deleted file mode 100644 index 348d5f1..0000000 --- a/vendor/github.com/stretchr/testify/assert/assertions.go +++ /dev/null @@ -1,1007 +0,0 @@ -package assert - -import ( - "bufio" - "bytes" - "encoding/json" - "fmt" - "math" - "reflect" - "regexp" - "runtime" - "strings" - "time" - "unicode" - "unicode/utf8" - - "github.com/davecgh/go-spew/spew" - "github.com/pmezard/go-difflib/difflib" -) - -// TestingT is an interface wrapper around *testing.T -type TestingT interface { - Errorf(format string, args ...interface{}) -} - -// Comparison a custom function that returns true on success and false on failure -type Comparison func() (success bool) - -/* - Helper functions -*/ - -// ObjectsAreEqual determines if two objects are considered equal. -// -// This function does no assertion of any kind. -func ObjectsAreEqual(expected, actual interface{}) bool { - - if expected == nil || actual == nil { - return expected == actual - } - - return reflect.DeepEqual(expected, actual) - -} - -// ObjectsAreEqualValues gets whether two objects are equal, or if their -// values are equal. -func ObjectsAreEqualValues(expected, actual interface{}) bool { - if ObjectsAreEqual(expected, actual) { - return true - } - - actualType := reflect.TypeOf(actual) - if actualType == nil { - return false - } - expectedValue := reflect.ValueOf(expected) - if expectedValue.IsValid() && expectedValue.Type().ConvertibleTo(actualType) { - // Attempt comparison after type conversion - return reflect.DeepEqual(expectedValue.Convert(actualType).Interface(), actual) - } - - return false -} - -/* CallerInfo is necessary because the assert functions use the testing object -internally, causing it to print the file:line of the assert method, rather than where -the problem actually occured in calling code.*/ - -// CallerInfo returns an array of strings containing the file and line number -// of each stack frame leading from the current test to the assert call that -// failed. -func CallerInfo() []string { - - pc := uintptr(0) - file := "" - line := 0 - ok := false - name := "" - - callers := []string{} - for i := 0; ; i++ { - pc, file, line, ok = runtime.Caller(i) - if !ok { - return nil - } - - // This is a huge edge case, but it will panic if this is the case, see #180 - if file == "" { - break - } - - parts := strings.Split(file, "/") - dir := parts[len(parts)-2] - file = parts[len(parts)-1] - if (dir != "assert" && dir != "mock" && dir != "require") || file == "mock_test.go" { - callers = append(callers, fmt.Sprintf("%s:%d", file, line)) - } - - f := runtime.FuncForPC(pc) - if f == nil { - break - } - name = f.Name() - // Drop the package - segments := strings.Split(name, ".") - name = segments[len(segments)-1] - if isTest(name, "Test") || - isTest(name, "Benchmark") || - isTest(name, "Example") { - break - } - } - - return callers -} - -// Stolen from the `go test` tool. -// isTest tells whether name looks like a test (or benchmark, according to prefix). -// It is a Test (say) if there is a character after Test that is not a lower-case letter. -// We don't want TesticularCancer. -func isTest(name, prefix string) bool { - if !strings.HasPrefix(name, prefix) { - return false - } - if len(name) == len(prefix) { // "Test" is ok - return true - } - rune, _ := utf8.DecodeRuneInString(name[len(prefix):]) - return !unicode.IsLower(rune) -} - -// getWhitespaceString returns a string that is long enough to overwrite the default -// output from the go testing framework. -func getWhitespaceString() string { - - _, file, line, ok := runtime.Caller(1) - if !ok { - return "" - } - parts := strings.Split(file, "/") - file = parts[len(parts)-1] - - return strings.Repeat(" ", len(fmt.Sprintf("%s:%d: ", file, line))) - -} - -func messageFromMsgAndArgs(msgAndArgs ...interface{}) string { - if len(msgAndArgs) == 0 || msgAndArgs == nil { - return "" - } - if len(msgAndArgs) == 1 { - return msgAndArgs[0].(string) - } - if len(msgAndArgs) > 1 { - return fmt.Sprintf(msgAndArgs[0].(string), msgAndArgs[1:]...) - } - return "" -} - -// Indents all lines of the message by appending a number of tabs to each line, in an output format compatible with Go's -// test printing (see inner comment for specifics) -func indentMessageLines(message string, tabs int) string { - outBuf := new(bytes.Buffer) - - for i, scanner := 0, bufio.NewScanner(strings.NewReader(message)); scanner.Scan(); i++ { - if i != 0 { - outBuf.WriteRune('\n') - } - for ii := 0; ii < tabs; ii++ { - outBuf.WriteRune('\t') - // Bizarrely, all lines except the first need one fewer tabs prepended, so deliberately advance the counter - // by 1 prematurely. - if ii == 0 && i > 0 { - ii++ - } - } - outBuf.WriteString(scanner.Text()) - } - - return outBuf.String() -} - -type failNower interface { - FailNow() -} - -// FailNow fails test -func FailNow(t TestingT, failureMessage string, msgAndArgs ...interface{}) bool { - Fail(t, failureMessage, msgAndArgs...) - - // We cannot extend TestingT with FailNow() and - // maintain backwards compatibility, so we fallback - // to panicking when FailNow is not available in - // TestingT. - // See issue #263 - - if t, ok := t.(failNower); ok { - t.FailNow() - } else { - panic("test failed and t is missing `FailNow()`") - } - return false -} - -// Fail reports a failure through -func Fail(t TestingT, failureMessage string, msgAndArgs ...interface{}) bool { - - message := messageFromMsgAndArgs(msgAndArgs...) - - errorTrace := strings.Join(CallerInfo(), "\n\r\t\t\t") - if len(message) > 0 { - t.Errorf("\r%s\r\tError Trace:\t%s\n"+ - "\r\tError:%s\n"+ - "\r\tMessages:\t%s\n\r", - getWhitespaceString(), - errorTrace, - indentMessageLines(failureMessage, 2), - message) - } else { - t.Errorf("\r%s\r\tError Trace:\t%s\n"+ - "\r\tError:%s\n\r", - getWhitespaceString(), - errorTrace, - indentMessageLines(failureMessage, 2)) - } - - return false -} - -// Implements asserts that an object is implemented by the specified interface. -// -// assert.Implements(t, (*MyInterface)(nil), new(MyObject), "MyObject") -func Implements(t TestingT, interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) bool { - - interfaceType := reflect.TypeOf(interfaceObject).Elem() - - if !reflect.TypeOf(object).Implements(interfaceType) { - return Fail(t, fmt.Sprintf("%T must implement %v", object, interfaceType), msgAndArgs...) - } - - return true - -} - -// IsType asserts that the specified objects are of the same type. -func IsType(t TestingT, expectedType interface{}, object interface{}, msgAndArgs ...interface{}) bool { - - if !ObjectsAreEqual(reflect.TypeOf(object), reflect.TypeOf(expectedType)) { - return Fail(t, fmt.Sprintf("Object expected to be of type %v, but was %v", reflect.TypeOf(expectedType), reflect.TypeOf(object)), msgAndArgs...) - } - - return true -} - -// Equal asserts that two objects are equal. -// -// assert.Equal(t, 123, 123, "123 and 123 should be equal") -// -// Returns whether the assertion was successful (true) or not (false). -func Equal(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool { - - if !ObjectsAreEqual(expected, actual) { - diff := diff(expected, actual) - return Fail(t, fmt.Sprintf("Not equal: %#v (expected)\n"+ - " != %#v (actual)%s", expected, actual, diff), msgAndArgs...) - } - - return true - -} - -// EqualValues asserts that two objects are equal or convertable to the same types -// and equal. -// -// assert.EqualValues(t, uint32(123), int32(123), "123 and 123 should be equal") -// -// Returns whether the assertion was successful (true) or not (false). -func EqualValues(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool { - - if !ObjectsAreEqualValues(expected, actual) { - return Fail(t, fmt.Sprintf("Not equal: %#v (expected)\n"+ - " != %#v (actual)", expected, actual), msgAndArgs...) - } - - return true - -} - -// Exactly asserts that two objects are equal is value and type. -// -// assert.Exactly(t, int32(123), int64(123), "123 and 123 should NOT be equal") -// -// Returns whether the assertion was successful (true) or not (false). -func Exactly(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool { - - aType := reflect.TypeOf(expected) - bType := reflect.TypeOf(actual) - - if aType != bType { - return Fail(t, fmt.Sprintf("Types expected to match exactly\n\r\t%v != %v", aType, bType), msgAndArgs...) - } - - return Equal(t, expected, actual, msgAndArgs...) - -} - -// NotNil asserts that the specified object is not nil. -// -// assert.NotNil(t, err, "err should be something") -// -// Returns whether the assertion was successful (true) or not (false). -func NotNil(t TestingT, object interface{}, msgAndArgs ...interface{}) bool { - if !isNil(object) { - return true - } - return Fail(t, "Expected value not to be nil.", msgAndArgs...) -} - -// isNil checks if a specified object is nil or not, without Failing. -func isNil(object interface{}) bool { - if object == nil { - return true - } - - value := reflect.ValueOf(object) - kind := value.Kind() - if kind >= reflect.Chan && kind <= reflect.Slice && value.IsNil() { - return true - } - - return false -} - -// Nil asserts that the specified object is nil. -// -// assert.Nil(t, err, "err should be nothing") -// -// Returns whether the assertion was successful (true) or not (false). -func Nil(t TestingT, object interface{}, msgAndArgs ...interface{}) bool { - if isNil(object) { - return true - } - return Fail(t, fmt.Sprintf("Expected nil, but got: %#v", object), msgAndArgs...) -} - -var numericZeros = []interface{}{ - int(0), - int8(0), - int16(0), - int32(0), - int64(0), - uint(0), - uint8(0), - uint16(0), - uint32(0), - uint64(0), - float32(0), - float64(0), -} - -// isEmpty gets whether the specified object is considered empty or not. -func isEmpty(object interface{}) bool { - - if object == nil { - return true - } else if object == "" { - return true - } else if object == false { - return true - } - - for _, v := range numericZeros { - if object == v { - return true - } - } - - objValue := reflect.ValueOf(object) - - switch objValue.Kind() { - case reflect.Map: - fallthrough - case reflect.Slice, reflect.Chan: - { - return (objValue.Len() == 0) - } - case reflect.Struct: - switch object.(type) { - case time.Time: - return object.(time.Time).IsZero() - } - case reflect.Ptr: - { - if objValue.IsNil() { - return true - } - switch object.(type) { - case *time.Time: - return object.(*time.Time).IsZero() - default: - return false - } - } - } - return false -} - -// Empty asserts that the specified object is empty. I.e. nil, "", false, 0 or either -// a slice or a channel with len == 0. -// -// assert.Empty(t, obj) -// -// Returns whether the assertion was successful (true) or not (false). -func Empty(t TestingT, object interface{}, msgAndArgs ...interface{}) bool { - - pass := isEmpty(object) - if !pass { - Fail(t, fmt.Sprintf("Should be empty, but was %v", object), msgAndArgs...) - } - - return pass - -} - -// NotEmpty asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either -// a slice or a channel with len == 0. -// -// if assert.NotEmpty(t, obj) { -// assert.Equal(t, "two", obj[1]) -// } -// -// Returns whether the assertion was successful (true) or not (false). -func NotEmpty(t TestingT, object interface{}, msgAndArgs ...interface{}) bool { - - pass := !isEmpty(object) - if !pass { - Fail(t, fmt.Sprintf("Should NOT be empty, but was %v", object), msgAndArgs...) - } - - return pass - -} - -// getLen try to get length of object. -// return (false, 0) if impossible. -func getLen(x interface{}) (ok bool, length int) { - v := reflect.ValueOf(x) - defer func() { - if e := recover(); e != nil { - ok = false - } - }() - return true, v.Len() -} - -// Len asserts that the specified object has specific length. -// Len also fails if the object has a type that len() not accept. -// -// assert.Len(t, mySlice, 3, "The size of slice is not 3") -// -// Returns whether the assertion was successful (true) or not (false). -func Len(t TestingT, object interface{}, length int, msgAndArgs ...interface{}) bool { - ok, l := getLen(object) - if !ok { - return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", object), msgAndArgs...) - } - - if l != length { - return Fail(t, fmt.Sprintf("\"%s\" should have %d item(s), but has %d", object, length, l), msgAndArgs...) - } - return true -} - -// True asserts that the specified value is true. -// -// assert.True(t, myBool, "myBool should be true") -// -// Returns whether the assertion was successful (true) or not (false). -func True(t TestingT, value bool, msgAndArgs ...interface{}) bool { - - if value != true { - return Fail(t, "Should be true", msgAndArgs...) - } - - return true - -} - -// False asserts that the specified value is false. -// -// assert.False(t, myBool, "myBool should be false") -// -// Returns whether the assertion was successful (true) or not (false). -func False(t TestingT, value bool, msgAndArgs ...interface{}) bool { - - if value != false { - return Fail(t, "Should be false", msgAndArgs...) - } - - return true - -} - -// NotEqual asserts that the specified values are NOT equal. -// -// assert.NotEqual(t, obj1, obj2, "two objects shouldn't be equal") -// -// Returns whether the assertion was successful (true) or not (false). -func NotEqual(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool { - - if ObjectsAreEqual(expected, actual) { - return Fail(t, fmt.Sprintf("Should not be: %#v\n", actual), msgAndArgs...) - } - - return true - -} - -// containsElement try loop over the list check if the list includes the element. -// return (false, false) if impossible. -// return (true, false) if element was not found. -// return (true, true) if element was found. -func includeElement(list interface{}, element interface{}) (ok, found bool) { - - listValue := reflect.ValueOf(list) - elementValue := reflect.ValueOf(element) - defer func() { - if e := recover(); e != nil { - ok = false - found = false - } - }() - - if reflect.TypeOf(list).Kind() == reflect.String { - return true, strings.Contains(listValue.String(), elementValue.String()) - } - - if reflect.TypeOf(list).Kind() == reflect.Map { - mapKeys := listValue.MapKeys() - for i := 0; i < len(mapKeys); i++ { - if ObjectsAreEqual(mapKeys[i].Interface(), element) { - return true, true - } - } - return true, false - } - - for i := 0; i < listValue.Len(); i++ { - if ObjectsAreEqual(listValue.Index(i).Interface(), element) { - return true, true - } - } - return true, false - -} - -// Contains asserts that the specified string, list(array, slice...) or map contains the -// specified substring or element. -// -// assert.Contains(t, "Hello World", "World", "But 'Hello World' does contain 'World'") -// assert.Contains(t, ["Hello", "World"], "World", "But ["Hello", "World"] does contain 'World'") -// assert.Contains(t, {"Hello": "World"}, "Hello", "But {'Hello': 'World'} does contain 'Hello'") -// -// Returns whether the assertion was successful (true) or not (false). -func Contains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) bool { - - ok, found := includeElement(s, contains) - if !ok { - return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", s), msgAndArgs...) - } - if !found { - return Fail(t, fmt.Sprintf("\"%s\" does not contain \"%s\"", s, contains), msgAndArgs...) - } - - return true - -} - -// NotContains asserts that the specified string, list(array, slice...) or map does NOT contain the -// specified substring or element. -// -// assert.NotContains(t, "Hello World", "Earth", "But 'Hello World' does NOT contain 'Earth'") -// assert.NotContains(t, ["Hello", "World"], "Earth", "But ['Hello', 'World'] does NOT contain 'Earth'") -// assert.NotContains(t, {"Hello": "World"}, "Earth", "But {'Hello': 'World'} does NOT contain 'Earth'") -// -// Returns whether the assertion was successful (true) or not (false). -func NotContains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) bool { - - ok, found := includeElement(s, contains) - if !ok { - return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", s), msgAndArgs...) - } - if found { - return Fail(t, fmt.Sprintf("\"%s\" should not contain \"%s\"", s, contains), msgAndArgs...) - } - - return true - -} - -// Condition uses a Comparison to assert a complex condition. -func Condition(t TestingT, comp Comparison, msgAndArgs ...interface{}) bool { - result := comp() - if !result { - Fail(t, "Condition failed!", msgAndArgs...) - } - return result -} - -// PanicTestFunc defines a func that should be passed to the assert.Panics and assert.NotPanics -// methods, and represents a simple func that takes no arguments, and returns nothing. -type PanicTestFunc func() - -// didPanic returns true if the function passed to it panics. Otherwise, it returns false. -func didPanic(f PanicTestFunc) (bool, interface{}) { - - didPanic := false - var message interface{} - func() { - - defer func() { - if message = recover(); message != nil { - didPanic = true - } - }() - - // call the target function - f() - - }() - - return didPanic, message - -} - -// Panics asserts that the code inside the specified PanicTestFunc panics. -// -// assert.Panics(t, func(){ -// GoCrazy() -// }, "Calling GoCrazy() should panic") -// -// Returns whether the assertion was successful (true) or not (false). -func Panics(t TestingT, f PanicTestFunc, msgAndArgs ...interface{}) bool { - - if funcDidPanic, panicValue := didPanic(f); !funcDidPanic { - return Fail(t, fmt.Sprintf("func %#v should panic\n\r\tPanic value:\t%v", f, panicValue), msgAndArgs...) - } - - return true -} - -// NotPanics asserts that the code inside the specified PanicTestFunc does NOT panic. -// -// assert.NotPanics(t, func(){ -// RemainCalm() -// }, "Calling RemainCalm() should NOT panic") -// -// Returns whether the assertion was successful (true) or not (false). -func NotPanics(t TestingT, f PanicTestFunc, msgAndArgs ...interface{}) bool { - - if funcDidPanic, panicValue := didPanic(f); funcDidPanic { - return Fail(t, fmt.Sprintf("func %#v should not panic\n\r\tPanic value:\t%v", f, panicValue), msgAndArgs...) - } - - return true -} - -// WithinDuration asserts that the two times are within duration delta of each other. -// -// assert.WithinDuration(t, time.Now(), time.Now(), 10*time.Second, "The difference should not be more than 10s") -// -// Returns whether the assertion was successful (true) or not (false). -func WithinDuration(t TestingT, expected, actual time.Time, delta time.Duration, msgAndArgs ...interface{}) bool { - - dt := expected.Sub(actual) - if dt < -delta || dt > delta { - return Fail(t, fmt.Sprintf("Max difference between %v and %v allowed is %v, but difference was %v", expected, actual, delta, dt), msgAndArgs...) - } - - return true -} - -func toFloat(x interface{}) (float64, bool) { - var xf float64 - xok := true - - switch xn := x.(type) { - case uint8: - xf = float64(xn) - case uint16: - xf = float64(xn) - case uint32: - xf = float64(xn) - case uint64: - xf = float64(xn) - case int: - xf = float64(xn) - case int8: - xf = float64(xn) - case int16: - xf = float64(xn) - case int32: - xf = float64(xn) - case int64: - xf = float64(xn) - case float32: - xf = float64(xn) - case float64: - xf = float64(xn) - default: - xok = false - } - - return xf, xok -} - -// InDelta asserts that the two numerals are within delta of each other. -// -// assert.InDelta(t, math.Pi, (22 / 7.0), 0.01) -// -// Returns whether the assertion was successful (true) or not (false). -func InDelta(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) bool { - - af, aok := toFloat(expected) - bf, bok := toFloat(actual) - - if !aok || !bok { - return Fail(t, fmt.Sprintf("Parameters must be numerical"), msgAndArgs...) - } - - if math.IsNaN(af) { - return Fail(t, fmt.Sprintf("Actual must not be NaN"), msgAndArgs...) - } - - if math.IsNaN(bf) { - return Fail(t, fmt.Sprintf("Expected %v with delta %v, but was NaN", expected, delta), msgAndArgs...) - } - - dt := af - bf - if dt < -delta || dt > delta { - return Fail(t, fmt.Sprintf("Max difference between %v and %v allowed is %v, but difference was %v", expected, actual, delta, dt), msgAndArgs...) - } - - return true -} - -// InDeltaSlice is the same as InDelta, except it compares two slices. -func InDeltaSlice(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) bool { - if expected == nil || actual == nil || - reflect.TypeOf(actual).Kind() != reflect.Slice || - reflect.TypeOf(expected).Kind() != reflect.Slice { - return Fail(t, fmt.Sprintf("Parameters must be slice"), msgAndArgs...) - } - - actualSlice := reflect.ValueOf(actual) - expectedSlice := reflect.ValueOf(expected) - - for i := 0; i < actualSlice.Len(); i++ { - result := InDelta(t, actualSlice.Index(i).Interface(), expectedSlice.Index(i).Interface(), delta) - if !result { - return result - } - } - - return true -} - -func calcRelativeError(expected, actual interface{}) (float64, error) { - af, aok := toFloat(expected) - if !aok { - return 0, fmt.Errorf("expected value %q cannot be converted to float", expected) - } - if af == 0 { - return 0, fmt.Errorf("expected value must have a value other than zero to calculate the relative error") - } - bf, bok := toFloat(actual) - if !bok { - return 0, fmt.Errorf("expected value %q cannot be converted to float", actual) - } - - return math.Abs(af-bf) / math.Abs(af), nil -} - -// InEpsilon asserts that expected and actual have a relative error less than epsilon -// -// Returns whether the assertion was successful (true) or not (false). -func InEpsilon(t TestingT, expected, actual interface{}, epsilon float64, msgAndArgs ...interface{}) bool { - actualEpsilon, err := calcRelativeError(expected, actual) - if err != nil { - return Fail(t, err.Error(), msgAndArgs...) - } - if actualEpsilon > epsilon { - return Fail(t, fmt.Sprintf("Relative error is too high: %#v (expected)\n"+ - " < %#v (actual)", actualEpsilon, epsilon), msgAndArgs...) - } - - return true -} - -// InEpsilonSlice is the same as InEpsilon, except it compares each value from two slices. -func InEpsilonSlice(t TestingT, expected, actual interface{}, epsilon float64, msgAndArgs ...interface{}) bool { - if expected == nil || actual == nil || - reflect.TypeOf(actual).Kind() != reflect.Slice || - reflect.TypeOf(expected).Kind() != reflect.Slice { - return Fail(t, fmt.Sprintf("Parameters must be slice"), msgAndArgs...) - } - - actualSlice := reflect.ValueOf(actual) - expectedSlice := reflect.ValueOf(expected) - - for i := 0; i < actualSlice.Len(); i++ { - result := InEpsilon(t, actualSlice.Index(i).Interface(), expectedSlice.Index(i).Interface(), epsilon) - if !result { - return result - } - } - - return true -} - -/* - Errors -*/ - -// NoError asserts that a function returned no error (i.e. `nil`). -// -// actualObj, err := SomeFunction() -// if assert.NoError(t, err) { -// assert.Equal(t, actualObj, expectedObj) -// } -// -// Returns whether the assertion was successful (true) or not (false). -func NoError(t TestingT, err error, msgAndArgs ...interface{}) bool { - if err != nil { - return Fail(t, fmt.Sprintf("Received unexpected error %q", err), msgAndArgs...) - } - - return true -} - -// Error asserts that a function returned an error (i.e. not `nil`). -// -// actualObj, err := SomeFunction() -// if assert.Error(t, err, "An error was expected") { -// assert.Equal(t, err, expectedError) -// } -// -// Returns whether the assertion was successful (true) or not (false). -func Error(t TestingT, err error, msgAndArgs ...interface{}) bool { - - message := messageFromMsgAndArgs(msgAndArgs...) - if err == nil { - return Fail(t, "An error is expected but got nil. %s", message) - } - - return true -} - -// EqualError asserts that a function returned an error (i.e. not `nil`) -// and that it is equal to the provided error. -// -// actualObj, err := SomeFunction() -// if assert.Error(t, err, "An error was expected") { -// assert.Equal(t, err, expectedError) -// } -// -// Returns whether the assertion was successful (true) or not (false). -func EqualError(t TestingT, theError error, errString string, msgAndArgs ...interface{}) bool { - - message := messageFromMsgAndArgs(msgAndArgs...) - if !NotNil(t, theError, "An error is expected but got nil. %s", message) { - return false - } - s := "An error with value \"%s\" is expected but got \"%s\". %s" - return Equal(t, errString, theError.Error(), - s, errString, theError.Error(), message) -} - -// matchRegexp return true if a specified regexp matches a string. -func matchRegexp(rx interface{}, str interface{}) bool { - - var r *regexp.Regexp - if rr, ok := rx.(*regexp.Regexp); ok { - r = rr - } else { - r = regexp.MustCompile(fmt.Sprint(rx)) - } - - return (r.FindStringIndex(fmt.Sprint(str)) != nil) - -} - -// Regexp asserts that a specified regexp matches a string. -// -// assert.Regexp(t, regexp.MustCompile("start"), "it's starting") -// assert.Regexp(t, "start...$", "it's not starting") -// -// Returns whether the assertion was successful (true) or not (false). -func Regexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) bool { - - match := matchRegexp(rx, str) - - if !match { - Fail(t, fmt.Sprintf("Expect \"%v\" to match \"%v\"", str, rx), msgAndArgs...) - } - - return match -} - -// NotRegexp asserts that a specified regexp does not match a string. -// -// assert.NotRegexp(t, regexp.MustCompile("starts"), "it's starting") -// assert.NotRegexp(t, "^start", "it's not starting") -// -// Returns whether the assertion was successful (true) or not (false). -func NotRegexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) bool { - match := matchRegexp(rx, str) - - if match { - Fail(t, fmt.Sprintf("Expect \"%v\" to NOT match \"%v\"", str, rx), msgAndArgs...) - } - - return !match - -} - -// Zero asserts that i is the zero value for its type and returns the truth. -func Zero(t TestingT, i interface{}, msgAndArgs ...interface{}) bool { - if i != nil && !reflect.DeepEqual(i, reflect.Zero(reflect.TypeOf(i)).Interface()) { - return Fail(t, fmt.Sprintf("Should be zero, but was %v", i), msgAndArgs...) - } - return true -} - -// NotZero asserts that i is not the zero value for its type and returns the truth. -func NotZero(t TestingT, i interface{}, msgAndArgs ...interface{}) bool { - if i == nil || reflect.DeepEqual(i, reflect.Zero(reflect.TypeOf(i)).Interface()) { - return Fail(t, fmt.Sprintf("Should not be zero, but was %v", i), msgAndArgs...) - } - return true -} - -// JSONEq asserts that two JSON strings are equivalent. -// -// assert.JSONEq(t, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`) -// -// Returns whether the assertion was successful (true) or not (false). -func JSONEq(t TestingT, expected string, actual string, msgAndArgs ...interface{}) bool { - var expectedJSONAsInterface, actualJSONAsInterface interface{} - - if err := json.Unmarshal([]byte(expected), &expectedJSONAsInterface); err != nil { - return Fail(t, fmt.Sprintf("Expected value ('%s') is not valid json.\nJSON parsing error: '%s'", expected, err.Error()), msgAndArgs...) - } - - if err := json.Unmarshal([]byte(actual), &actualJSONAsInterface); err != nil { - return Fail(t, fmt.Sprintf("Input ('%s') needs to be valid json.\nJSON parsing error: '%s'", actual, err.Error()), msgAndArgs...) - } - - return Equal(t, expectedJSONAsInterface, actualJSONAsInterface, msgAndArgs...) -} - -func typeAndKind(v interface{}) (reflect.Type, reflect.Kind) { - t := reflect.TypeOf(v) - k := t.Kind() - - if k == reflect.Ptr { - t = t.Elem() - k = t.Kind() - } - return t, k -} - -// diff returns a diff of both values as long as both are of the same type and -// are a struct, map, slice or array. Otherwise it returns an empty string. -func diff(expected interface{}, actual interface{}) string { - if expected == nil || actual == nil { - return "" - } - - et, ek := typeAndKind(expected) - at, _ := typeAndKind(actual) - - if et != at { - return "" - } - - if ek != reflect.Struct && ek != reflect.Map && ek != reflect.Slice && ek != reflect.Array { - return "" - } - - spew.Config.SortKeys = true - e := spew.Sdump(expected) - a := spew.Sdump(actual) - - diff, _ := difflib.GetUnifiedDiffString(difflib.UnifiedDiff{ - A: difflib.SplitLines(e), - B: difflib.SplitLines(a), - FromFile: "Expected", - FromDate: "", - ToFile: "Actual", - ToDate: "", - Context: 1, - }) - - return "\n\nDiff:\n" + diff -} diff --git a/vendor/github.com/stretchr/testify/assert/doc.go b/vendor/github.com/stretchr/testify/assert/doc.go deleted file mode 100644 index c9dccc4..0000000 --- a/vendor/github.com/stretchr/testify/assert/doc.go +++ /dev/null @@ -1,45 +0,0 @@ -// Package assert provides a set of comprehensive testing tools for use with the normal Go testing system. -// -// Example Usage -// -// The following is a complete example using assert in a standard test function: -// import ( -// "testing" -// "github.com/stretchr/testify/assert" -// ) -// -// func TestSomething(t *testing.T) { -// -// var a string = "Hello" -// var b string = "Hello" -// -// assert.Equal(t, a, b, "The two words should be the same.") -// -// } -// -// if you assert many times, use the format below: -// -// import ( -// "testing" -// "github.com/stretchr/testify/assert" -// ) -// -// func TestSomething(t *testing.T) { -// assert := assert.New(t) -// -// var a string = "Hello" -// var b string = "Hello" -// -// assert.Equal(a, b, "The two words should be the same.") -// } -// -// Assertions -// -// Assertions allow you to easily write test code, and are global funcs in the `assert` package. -// All assertion functions take, as the first argument, the `*testing.T` object provided by the -// testing framework. This allows the assertion funcs to write the failings and other details to -// the correct place. -// -// Every assertion function also takes an optional string message as the final argument, -// allowing custom error messages to be appended to the message the assertion method outputs. -package assert diff --git a/vendor/github.com/stretchr/testify/assert/errors.go b/vendor/github.com/stretchr/testify/assert/errors.go deleted file mode 100644 index ac9dc9d..0000000 --- a/vendor/github.com/stretchr/testify/assert/errors.go +++ /dev/null @@ -1,10 +0,0 @@ -package assert - -import ( - "errors" -) - -// AnError is an error instance useful for testing. If the code does not care -// about error specifics, and only needs to return the error for example, this -// error should be used to make the test code more readable. -var AnError = errors.New("assert.AnError general error for testing") diff --git a/vendor/github.com/stretchr/testify/assert/forward_assertions.go b/vendor/github.com/stretchr/testify/assert/forward_assertions.go deleted file mode 100644 index b867e95..0000000 --- a/vendor/github.com/stretchr/testify/assert/forward_assertions.go +++ /dev/null @@ -1,16 +0,0 @@ -package assert - -// Assertions provides assertion methods around the -// TestingT interface. -type Assertions struct { - t TestingT -} - -// New makes a new Assertions object for the specified TestingT. -func New(t TestingT) *Assertions { - return &Assertions{ - t: t, - } -} - -//go:generate go run ../_codegen/main.go -output-package=assert -template=assertion_forward.go.tmpl diff --git a/vendor/github.com/stretchr/testify/assert/http_assertions.go b/vendor/github.com/stretchr/testify/assert/http_assertions.go deleted file mode 100644 index e1b9442..0000000 --- a/vendor/github.com/stretchr/testify/assert/http_assertions.go +++ /dev/null @@ -1,106 +0,0 @@ -package assert - -import ( - "fmt" - "net/http" - "net/http/httptest" - "net/url" - "strings" -) - -// httpCode is a helper that returns HTTP code of the response. It returns -1 -// if building a new request fails. -func httpCode(handler http.HandlerFunc, method, url string, values url.Values) int { - w := httptest.NewRecorder() - req, err := http.NewRequest(method, url+"?"+values.Encode(), nil) - if err != nil { - return -1 - } - handler(w, req) - return w.Code -} - -// HTTPSuccess asserts that a specified handler returns a success status code. -// -// assert.HTTPSuccess(t, myHandler, "POST", "http://www.google.com", nil) -// -// Returns whether the assertion was successful (true) or not (false). -func HTTPSuccess(t TestingT, handler http.HandlerFunc, method, url string, values url.Values) bool { - code := httpCode(handler, method, url, values) - if code == -1 { - return false - } - return code >= http.StatusOK && code <= http.StatusPartialContent -} - -// HTTPRedirect asserts that a specified handler returns a redirect status code. -// -// assert.HTTPRedirect(t, myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} -// -// Returns whether the assertion was successful (true) or not (false). -func HTTPRedirect(t TestingT, handler http.HandlerFunc, method, url string, values url.Values) bool { - code := httpCode(handler, method, url, values) - if code == -1 { - return false - } - return code >= http.StatusMultipleChoices && code <= http.StatusTemporaryRedirect -} - -// HTTPError asserts that a specified handler returns an error status code. -// -// assert.HTTPError(t, myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} -// -// Returns whether the assertion was successful (true) or not (false). -func HTTPError(t TestingT, handler http.HandlerFunc, method, url string, values url.Values) bool { - code := httpCode(handler, method, url, values) - if code == -1 { - return false - } - return code >= http.StatusBadRequest -} - -// HTTPBody is a helper that returns HTTP body of the response. It returns -// empty string if building a new request fails. -func HTTPBody(handler http.HandlerFunc, method, url string, values url.Values) string { - w := httptest.NewRecorder() - req, err := http.NewRequest(method, url+"?"+values.Encode(), nil) - if err != nil { - return "" - } - handler(w, req) - return w.Body.String() -} - -// HTTPBodyContains asserts that a specified handler returns a -// body that contains a string. -// -// assert.HTTPBodyContains(t, myHandler, "www.google.com", nil, "I'm Feeling Lucky") -// -// Returns whether the assertion was successful (true) or not (false). -func HTTPBodyContains(t TestingT, handler http.HandlerFunc, method, url string, values url.Values, str interface{}) bool { - body := HTTPBody(handler, method, url, values) - - contains := strings.Contains(body, fmt.Sprint(str)) - if !contains { - Fail(t, fmt.Sprintf("Expected response body for \"%s\" to contain \"%s\" but found \"%s\"", url+"?"+values.Encode(), str, body)) - } - - return contains -} - -// HTTPBodyNotContains asserts that a specified handler returns a -// body that does not contain a string. -// -// assert.HTTPBodyNotContains(t, myHandler, "www.google.com", nil, "I'm Feeling Lucky") -// -// Returns whether the assertion was successful (true) or not (false). -func HTTPBodyNotContains(t TestingT, handler http.HandlerFunc, method, url string, values url.Values, str interface{}) bool { - body := HTTPBody(handler, method, url, values) - - contains := strings.Contains(body, fmt.Sprint(str)) - if contains { - Fail(t, "Expected response body for %s to NOT contain \"%s\" but found \"%s\"", url+"?"+values.Encode(), str, body) - } - - return !contains -} diff --git a/vendor/github.com/yesnault/hashtag/README.md b/vendor/github.com/yesnault/hashtag/README.md deleted file mode 100644 index 6219a44..0000000 --- a/vendor/github.com/yesnault/hashtag/README.md +++ /dev/null @@ -1,39 +0,0 @@ -# hashtag -Package hashtag implements extraction of Twitter type hashtags, mentions and -replies form text in Go. This package partially ports extraction routines from -[Twitter's official Java package](https://github.com/twitter/twitter-text) -to Go and runs most of the standard twitter-text conformance tests. It does not -yet implement URL extraction (and hence URL/Hashtag overlaps), cashtags and lists - -Since the package attempts to closely follow the Twitter-Text Java API, function -names may be longer than typical Go package function names - -Installation ------------- -Note: As the package matures, I plan to move this to gopkg.in -``` -go get github.com/srinathh/hashtag -``` - -Usage ------ -Import the package as -``` -import "github.com/srinathh/hashtag" -``` - -This package supports the following functions to extract hashtags and mentions -with or without position markers. The functions omit # and @ characters -(and also their higher unicode number counterparts @ and #) from return values -- `ExtractHashtags(text string) []string` -- `ExtractHashtagsWithIndices(text string) []Entity` -- `ExtractMentions(text string) []string` -- `ExtractMentionsWithIndices(text string) []Entity` -- `ExtractReply(text string) string` - -Documentation -------------- -Read the full documentation and examples on [GoDoc](http://godoc.org/github.com/srinathh/hashtag) - - - diff --git a/vendor/github.com/yesnault/hashtag/hashtag.go b/vendor/github.com/yesnault/hashtag/hashtag.go deleted file mode 100644 index cd88317..0000000 --- a/vendor/github.com/yesnault/hashtag/hashtag.go +++ /dev/null @@ -1,201 +0,0 @@ -/* - Copyright 2014 Hariharan Srinath - - 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 hashtag implements extraction of Twitter type hashtags, mentions and -replies form text in Go. This package partially ports extraction routines from -Twitter's official Java package at https://github.com/twitter/twitter-text -to Go and runs most of the standard twitter-text conformance tests. It does not -yet implement URL extraction (and hence URL/Hashtag overlaps), cashtags and lists - -Since the package attempts to closely follow the Twitter-Text Java API, function -names may be longer than typical Go package function names -*/ -package hashtag - -import ( - "regexp" - "strings" -) - -const ( - unicodeSpaces = "[" + - "\\x{0009}-\\x{000d}" + // # White_Space # Cc [5] .. - "\\x{0020}" + // White_Space # Zs SPACE - "\\x{0085}" + // White_Space # Cc - "\\x{00a0}" + // White_Space # Zs NO-BREAK SPACE - "\\x{1680}" + // White_Space # Zs OGHAM SPACE MARK - "\\x{180E}" + // White_Space # Zs MONGOLIAN VOWEL SEPARATOR - "\\x{2000}-\\x{200a}" + // # White_Space # Zs [11] EN QUAD..HAIR SPACE - "\\x{2028}" + // White_Space # Zl LINE SEPARATOR - "\\x{2029}" + // White_Space # Zp PARAGRAPH SEPARATOR - "\\x{202F}" + // White_Space # Zs NARROW NO-BREAK SPACE - "\\x{205F}" + // White_Space # Zs MEDIUM MATHEMATICAL SPACE - "\\x{3000}" + // White_Space # Zs IDEOGRAPHIC SPACE - "]" - - hashtagLetters = "\\pL\\pM" - hashtagNumerals = "\\p{Nd}" - hashtagSpecialChars = "/" + "\\." + "_" + "\\-" + "\\:" + "\\+" + "@" + "?" + "&" + "~" + "=" + "," + - "\\x{200c}" + // ZERO WIDTH NON-JOINER (ZWNJ) - "\\x{200d}" + // ZERO WIDTH JOINER (ZWJ) - "\\x{a67e}" + // CYRILLIC KAVYKA - "\\x{05be}" + // HEBREW PUNCTUATION MAQAF - "\\x{05f3}" + // HEBREW PUNCTUATION GERESH - "\\x{05f4}" + // HEBREW PUNCTUATION GERSHAYIM - "\\x{309b}" + // KATAKANA-HIRAGANA VOICED SOUND MARK - "\\x{309c}" + // KATAKANA-HIRAGANA SEMI-VOICED SOUND MARK - "\\x{30a0}" + // KATAKANA-HIRAGANA DOUBLE HYPHEN - "\\x{30fb}" + // KATAKANA MIDDLE DOT - "\\x{3003}" + // DITTO MARK - "\\x{0f0b}" + // TIBETAN MARK INTERSYLLABIC TSHEG - "\\x{0f0c}" + // TIBETAN MARK DELIMITER TSHEG BSTAR - "\\x{0f0d}" // TIBETAN MARK SHAD - - hashtagLettersNumerals = hashtagLetters + hashtagNumerals + hashtagSpecialChars - hashtagLettersNumeralsSet = "[" + hashtagLettersNumerals + "]" - hashtagLettersSet = "[:" + hashtagLetters + "]" - - atSignsChars = "@\\x{FF20}" - atSigns = "[" + atSignsChars + "]" - - latinAccentsChars = "\\x{00c0}-\\x{00d6}\\x{00d8}-\\x{00f6}\\x{00f8}-\\x{00ff}" + // Latin-1 - "\\x{0100}-\\x{024f}" + // Latin Extended A and B - "\\x{0253}\\x{0254}\\x{0256}\\x{0257}\\x{0259}\\x{025b}\\x{0263}\\x{0268}\\x{026f}\\x{0272}\\x{0289}\\x{028b}" + // IPA Extensions - "\\x{02bb}" + // Hawaiian - "\\x{0300}-\\x{036f}" + // Combining diacritics - "\\x{1e00}-\\x{1eff}" // Latin Extended Additional (mostly for Vietnamese) -) - -var validMention = regexp.MustCompile("([^A-Za-z0-9_!#$%&*" + atSignsChars + "]|^|[Rr][tT]:?)(" + atSigns + "+)([A-Za-z0-9_\\.\\-]{1,20})") - -var invalidMentionMatchEnd = regexp.MustCompile("^(?:[" + atSignsChars + latinAccentsChars + "]|://)") - -var validHashtag = regexp.MustCompile("(?m)(?:^|[^&" + hashtagLettersNumerals + "])(?:#|\\x{FF03})(" + - hashtagLettersNumeralsSet + "*" + hashtagLettersSet + hashtagLettersNumeralsSet + - "*)") - -var invalidHashtagMatchEnd = regexp.MustCompile("^(?:[##])") - -var validReply = regexp.MustCompile("^(?:" + unicodeSpaces + ")*" + atSigns + "([A-Za-z0-9_]{1,20})") - -/* -Entity is used by ExtractXXXXWithIndices functions to return the position -and text extracted. This may be expanded in the future to support List slugs -*/ -type Entity struct { - Start int - End int - Value string -} - -/* -ExtractHashtags extracts hashtags without the hash markers from input -text and returns them as a slice of strings. -*/ -func ExtractHashtags(text string) []string { - entities := ExtractHashtagsWithIndices(text) - ret := make([]string, len(entities)) - - for j, entity := range entities { - ret[j] = entity.Value - } - return ret -} - -/* -ExtractHashtagsWithIndices extracts hashtags without the hash markers from -input text and returns them as a slice of Entities containing start/end positions. -*/ -func ExtractHashtagsWithIndices(text string) []Entity { - if len(text) == 0 || !strings.ContainsAny(text, "#\uFF03") { - return []Entity{} - } - - matches := validHashtag.FindAllStringSubmatchIndex(text, -1) - entities := []Entity{} - - for _, match := range matches { - if !invalidHashtagMatchEnd.MatchString(text[match[1]:]) { - value := text[match[2]:match[3]] - /*if strings.Contains(value, "://") { - continue - }*/ - entities = append(entities, Entity{ - Start: match[2], - End: match[3], - Value: value, - }) - } - } - return entities -} - -/* -ExtractMentionsWithIndices extracts mentions without the @ markers from -input text and returns them as a slice of Entities containing start/end positions. -*/ -func ExtractMentionsWithIndices(text string) []Entity { - if len(text) == 0 || !strings.ContainsAny(text, "@@") { - return []Entity{} - } - - matches := validMention.FindAllStringSubmatchIndex(text, -1) - entities := []Entity{} - for _, match := range matches { - if !invalidMentionMatchEnd.MatchString(text[match[1]:]) { - entities = append(entities, Entity{ - Start: match[6], - End: match[7], - Value: text[match[6]:match[7]], - }) - } - } - return entities -} - -/* -ExtractMentions extracts mentions without the @ markers from -input text and returns them as a slice of strings. -*/ -func ExtractMentions(text string) []string { - entities := ExtractMentionsWithIndices(text) - ret := make([]string, len(entities)) - - for j, ent := range entities { - ret[j] = ent.Value - } - return ret -} - -/* -ExtractReply extracts reply username without the -@ marker from input text and returns it as a string. -Empty string signals no reply username -*/ -func ExtractReply(text string) string { - if len(text) == 0 || !strings.ContainsAny(text, "@@") { - return "" - } - - matches := validReply.FindAllStringSubmatchIndex(text, -1) - for _, match := range matches { - if !invalidMentionMatchEnd.MatchString(text[match[1]:]) { - return text[match[2]:match[3]] - } - } - return "" -} diff --git a/vendor/github.com/yesnault/hashtag/tests.yml b/vendor/github.com/yesnault/hashtag/tests.yml deleted file mode 100644 index a16365f..0000000 --- a/vendor/github.com/yesnault/hashtag/tests.yml +++ /dev/null @@ -1,475 +0,0 @@ -mentions: - - description: "Test fastpath exit without mentions" - text: "no mentions in this #text" - expected: [] - - - description: "Extract mention at the begining of a tweet" - text: "@username reply" - expected: ["username"] - - - description: "Extract mention at the end of a tweet" - text: "mention @username" - expected: ["username"] - - - description: "Extract mention in the middle of a tweet" - text: "mention @username in the middle" - expected: ["username"] - - - description: "Extract mention of username with underscore" - text: "mention @user_name" - expected: ["user_name"] - - - description: "Extract mention of all numeric username" - text: "mention @12345" - expected: ["12345"] - - - description: "Extract mention with dot" - text: "mention @aaa.bbb" - expected: ["aaa.bbb"] - - - description: "Extract mention with -" - text: "mention @aaa-bbb" - expected: ["aaa-bbb"] - - - description: "Extract mention or multiple usernames" - text: "mention @username1 @username2" - expected: ["username1", "username2"] - - - description: "Extract mention in the middle of a Japanese tweet" - text: "の@usernameに到着を待っている" - expected: ["username"] - - - description: "DO NOT extract username ending in @" - text: "Current Status: @_@ (cc: @username)" - expected: ["username"] - - - description: "DO NOT extract username followed by accented latin characters" - text: "@aliceìnheiro something something" - expected: [] - - - description: "Extract lone metion but not @user@user (too close to an email)" - text: "@username email me @test@example.com" - expected: ["username"] - - - description: "DO NOT extract 'http' in '@http://' as username" - text: "@http://twitter.com" - expected: [] - - - description: "Extract mentions before newline" - text: "@username\n@mention" - expected: ["username", "mention"] - - - description: "Extract mentions after 'RT'" - text: "RT@username RT:@mention RT @test" - expected: ["username", "mention", "test"] - - - description: "Extract mentions after 'rt'" - text: "rt@username rt:@mention rt @test" - expected: ["username", "mention", "test"] - - - description: "Extract mentions after 'Rt'" - text: "Rt@username Rt:@mention Rt @test" - expected: ["username", "mention", "test"] - - - description: "Extract mentions after 'rT'" - text: "rT@username rT:@mention rT @test" - expected: ["username", "mention", "test"] - - - description: "DO NOT extract username preceded by !" - text: "f!@kn" - expected: [] - - - description: "DO NOT extract username preceded by @" - text: "f@@kn" - expected: [] - - - description: "DO NOT extract username preceded by #" - text: "f#@kn" - expected: [] - - - description: "DO NOT extract username preceded by $" - text: "f$@kn" - expected: [] - - - description: "DO NOT extract username preceded by %" - text: "f%@kn" - expected: [] - - - description: "DO NOT extract username preceded by &" - text: "f&@kn" - expected: [] - - - description: "DO NOT extract username preceded by *" - text: "f*@kn" - expected: [] - - - description: "Extract a mention at the start" - text: "@username yo!" - expected: ["username"] - - - description: "Extract a mention that has the same thing mentioned at the start" - text: "username @username" - expected: ["username"] - - - description: "Extract a mention in the middle of a Japanese tweet" - text: "の@usernameに到着を待っている" - expected: ["username"] - -replies: - - description: "Test fastpath exit without replies" - text: "no replies in this #text" - expected: [] - - - description: "Extract reply at the begining of a tweet" - text: "@username reply" - expected: ["username"] - - - description: "Extract reply preceded by only a space" - text: " @username reply" - expected: ["username"] - - - description: "Extract reply preceded by only a full-width space (U+3000)" - text: " @username reply" - expected: ["username"] - - - description: "DO NOT Extract reply when preceded by text" - text: "a @username mention, not a reply" - expected: [] - - - description: "DO NOT Extract reply when preceded by ." - text: ".@username mention, not a reply" - expected: [] - - - description: "DO NOT Extract reply when preceded by /" - text: "/@username mention, not a reply" - expected: [] - - - description: "DO NOT Extract reply when preceded by _" - text: "_@username mention, not a reply" - expected: [] - - - description: "DO NOT Extract reply when preceded by -" - text: "-@username mention, not a reply" - expected: [] - - - description: "DO NOT Extract reply when preceded by +" - text: "+@username mention, not a reply" - expected: [] - - - description: "DO NOT Extract reply when preceded by #" - text: "#@username mention, not a reply" - expected: [] - - - description: "DO NOT Extract reply when preceded by !" - text: "!@username mention, not a reply" - expected: [] - - - description: "DO NOT Extract reply when preceded by @" - text: "@@username mention, not a reply" - expected: [] - - - description: "DO NOT Extract reply when followed by URL" - text: "@http://twitter.com" - expected: [] - -hashtags: - - description: "Test fastpath exit without hashtags" - text: "nothing like @hashtags in this text" - expected: [] - - - description: "Extract an all-alpha hashtag" - text: "a #hashtag here" - expected: ["hashtag"] - - - description: "Extract a letter-then-number hashtag" - text: "this is #hashtag1" - expected: ["hashtag1"] - - - description: "Extract a number-then-letter hashtag" - text: "#1hashtag is this" - expected: ["1hashtag"] - - - description: "DO NOT Extract an all-numeric hashtag" - text: "On the #16 bus" - expected: [] - - - description: "DO NOT Extract a single numeric hashtag" - text: "#0" - expected: [] - - - description: "Extract hashtag after bracket" - text: "(#hashtag1 )#hashtag2 [#hashtag3 ]#hashtag4 ’#hashtag5’#hashtag6" - expected: ["hashtag1", "hashtag2", "hashtag3", "hashtag4", "hashtag5", "hashtag6"] - - - description: "Extract a hashtag containing ñ" - text: "I'll write more tests #mañana" - expected: ["mañana"] - - - description: "Extract a hashtag containing é" - text: "Working remotely #café" - expected: ["café"] - - - description: "Extract a hashtag containing ü" - text: "Getting my Oktoberfest on #münchen" - expected: ["münchen"] - - - description: "DO NOT Extract a hashtag containing Japanese" - text: "this is not valid: # 会議中 ハッシュ" - expected: [] - - - description: "Extract a hashtag in Korean" - text: "What is #트위터 anyway?" - expected: ["트위터"] - - - description: "Extract a half-width Hangul hashtag" - text: "Just random half-width Hangul #ᆪᆭᄚ" - expected: ["ᆪᆭᄚ"] - - - description: "Extract a hashtag in Russian" - text: "What is #ашок anyway?" - expected: ["ашок"] - - - description: "Extract a starting katakana hashtag" - text: "#カタカナ is a hashtag" - expected: ["カタカナ"] - - - description: "Extract a starting hiragana hashtag" - text: "#ひらがな FTW!" - expected: ["ひらがな"] - - - description: "Extract a starting kanji hashtag" - text: "#漢字 is the future" - expected: ["漢字"] - - - description: "Extract a trailing katakana hashtag" - text: "Hashtag #カタカナ" - expected: ["カタカナ"] - - - description: "Extract a trailing hiragana hashtag" - text: "Japanese hashtags #ひらがな" - expected: ["ひらがな"] - - - description: "Extract a trailing kanji hashtag" - text: "Study time #漢字" - expected: ["漢字"] - - - description: "Extract a central katakana hashtag" - text: "See my #カタカナ hashtag?" - expected: ["カタカナ"] - - - description: "Extract a central hiragana hashtag" - text: "Study #ひらがな for fun and profit" - expected: ["ひらがな"] - - - description: "Extract a central kanji hashtag" - text: "Some say #漢字 is the past. what do they know?" - expected: ["漢字"] - - - description: "Extract a Kanji/Katakana mixed hashtag" - text: "日本語ハッシュタグテスト #日本語ハッシュタグ" - expected: ["日本語ハッシュタグ"] - - - description: "Extract a hashtag after a punctuation" - text: "日本語ハッシュテスト。#日本語ハッシュタグ" - expected: ["日本語ハッシュタグ"] - - - description: "DO NOT include a punctuation in a hashtag" - text: "#日本語ハッシュタグ。" - expected: ["日本語ハッシュタグ"] - - - description: "Extract a full-width Alnum hashtag" - text: "全角英数字ハッシュタグ #hashtag123" - expected: ["hashtag123"] - - - description: "DO NOT extract a hashtag without a preceding space" - text: "日本語ハッシュタグ#日本語ハッシュタグ" - expected: [] - - - description: "Hashtag with chouon" - text: "長音ハッシュタグ。#サッカー" - expected: ["サッカー"] - - - description: "Hashtag with half-width chouon" - text: "長音ハッシュタグ。#サッカー" - expected: ["サッカー"] - - - description: "Hashtag with half-widh voiced sounds marks" - text: "#ハッシュタグ #パピプペポ" - expected: ["ハッシュタグ", "パピプペポ"] - - - description: "Hashtag with half-width # after full-width !" - text: "できましたよー!#日本語ハッシュタグ。" - expected: ["日本語ハッシュタグ"] - - - description: "Hashtag with full-width # after full-width !" - text: "できましたよー!#日本語ハッシュタグ。" - expected: ["日本語ハッシュタグ"] - - - description: "Hashtag with ideographic iteration mark" - text: "#云々 #学問のすゝめ #いすゞ #各〻 #各〃" - expected: ["云々", "学問のすゝめ", "いすゞ", "各〻", "各〃"] - - - description: "Hashtags with ş (U+015F)" - text: "Here’s a test tweet for you: #Ateş #qrşt #ştu #ş" - expected: ["Ateş", "qrşt", "ştu", "ş"] - - - description: "Hashtags with İ (U+0130) and ı (U+0131)" - text: "Here’s a test tweet for you: #İn #ın" - expected: ["İn", "ın"] - - - description: "Hashtag before punctuations, except:" - text: "#hashtag: #hashtag; #hashtag, #hashtag. #hashtag!" - expected: ["hashtag:", "hashtag", "hashtag,", "hashtag.", "hashtag"] - - - description: "Hashtag with dot:" - text: "#hashtag.dot" - expected: ["hashtag.dot"] - - - description: "Hashtag with /" - text: "#From_dev/aa #From_aa/ff" - expected: ["From_dev/aa", "From_aa/ff"] - - - description: "Hashtag with:" - text: "#From:dev/aa #From:aa/ff" - expected: ["From:dev/aa", "From:aa/ff"] - - - description: "Hashtag with ?:" - text: "#From:dev?aa #From:aa?ff" - expected: ["From:dev?aa", "From:aa?ff"] - - - description: "Hashtag with =:" - text: "#From:dev=aa #From:aa=ff" - expected: ["From:dev=aa", "From:aa=ff"] - - - description: "Hashtag with -:" - text: "#From:dev-aa #From:aa-ff" - expected: ["From:dev-aa", "From:aa-ff"] - - - description: "Hashtag with ~:" - text: "#From:dev~aa #From:aa~ff" - expected: ["From:dev~aa", "From:aa~ff"] - - - description: "Hashtag with ,:" - text: "#From:dev,aa #From:aa,ff" - expected: ["From:dev,aa", "From:aa,ff"] - -# - description: "Hashtag after punctuations" -# text: ":#hashtaga ;#hashtagb ,#hashtagc .#hashtagd ?#hashtagf" -# expected: ["hashtaga", "hashtagb", "hashtagc", "hashtagd", "hashtagf"] - - - description: "Hashtag with http://" - text: "#hop:http://hashtaga" - expected: ["hop:http://hashtaga"] - - - description: "Hashtag with :/" - text: "#http:/hashtaga" - expected: ["http:/hashtaga"] - - - description: "Hashtag with http:aa" - text: "#http:aa" - expected: ["http:aa"] - - - description: "Hashtag before newline" - text: "#hashtag\ntest\n#hashtag2\ntest\n#hashtag3\n" - expected: ["hashtag", "hashtag2", "hashtag3"] - - - description: "Extract hashtag when # is followed by URL" - text: "#http://twitter.com #https://twitter.com" - expected: ["http://twitter.com", "https://twitter.com"] - -# Checking for overlap of hashtag with URL is not implemented currently -# - description: "DO NOT extract hashtag if it's a part of URL" -# text: "http://twitter.com/#hashtag twitter.com/#hashtag" -# expected: [] - - - description: "Extract hashtags with Latin extended characters" - text: "#Azərbaycanca #mûǁae #Čeština #Ċaoiṁín" - expected: ["Azərbaycanca", "mûǁae", "Čeština", "Ċaoiṁín"] - - - description: "Extract Arabic hashtags" - text: "#سیاست #ایران #السياسة #السياح #لغات #اتمی #کنفرانس #العربية #الجزيرة #فارسی" - expected: ["سیاست", "ایران", "السياسة", "السياح", "لغات", "اتمی", "کنفرانس", "العربية", "الجزيرة", "فارسی"] - - - description: "Extract Hebrew hashtags" - text: "#עַל־יְדֵי #וכו׳ #מ״כ" - expected: ["עַל־יְדֵי", "וכו׳", "מ״כ"] - - - description: "Extract Thai hashtags" - text: "#ผู้เริ่ม #การเมือง #รายละเอียด #นักท่องเที่ยว #ของขวัญ #สนามบิน #เดินทาง #ประธาน" - expected: ["ผู้เริ่ม", "การเมือง", "รายละเอียด", "นักท่องเที่ยว", "ของขวัญ", "สนามบิน", "เดินทาง", "ประธาน"] - - - description: "Extract Arabic hashtags with Zero-Width Non-Joiner" - text: "#أي‌بي‌إم #می‌خواهم" - expected: ["أي‌بي‌إم", "می‌خواهم"] - - - description: "Extract Amharic hashtag" - text: "የአላህ መልእክተኛ ሰለላሁ ዓለይሂ ወሰለም #ኢትዮሙስሊምስ" - expected: ["ኢትዮሙስሊምስ"] - - - description: "Extract Sinhala hashtag with Zero-Width Joiner (U+200D)" - text: "#ශ්‍රීලංකා" - expected: ["ශ්‍රීලංකා"] - - - description: "Extract Arabic and Persian hashtags with numbers" - text: "#۳۴۵هشتگ #هشتگ۶۷۸ #ســـلام_عليكم_٤٠٦" - expected: ["۳۴۵هشتگ","هشتگ۶۷۸","ســـلام_عليكم_٤٠٦"] - - - description: "Extract Hindi hashtags" - text: "#महात्मा #महात्मा_१२३४ #१२३४ गांधी" - expected: ["महात्मा","महात्मा_१२३४"] - - - description: "Extract Indic script hashtags" - text: "#বাংলা #ગુજરાતી #ಕನ್ನಡ #മലയാളം #ଓଡ଼ିଆ #ਪੰਜਾਬੀ #සිංහල #தமிழ் #తెలుగు" - expected: ["বাংলা","ગુજરાતી","ಕನ್ನಡ","മലയാളം","ଓଡ଼ିଆ","ਪੰਜਾਬੀ","සිංහල","தமிழ்","తెలుగు"] - - - description: "Extract Tibetan hashtags" - text: "#བོད་སྐད་ #བོད་སྐད།" - expected: ["བོད་སྐད་","བོད་སྐད།"] - - - description: "Extract Khmer, Burmese, Laotian hashtags" - text: "#មហាត្មះគន្ធី #မြင့်မြတ်သော #ຊີວະສາດ" - expected: ["មហាត្មះគន្ធី","မြင့်မြတ်သော","ຊີວະສາດ"] - - - description: "Extract Greek hashtag" - text: "#Μαχάτμα_Γκάντι ήταν Ινδός πολιτικός" - expected: ["Μαχάτμα_Γκάντι"] - - - description: "Extract Armenian and Georgian hashtags" - text: "#Մահաթմա #მაჰათმა" - expected: ["Մահաթմա","მაჰათმა"] - - - description: "DO NOT extract hashtags without a letter" - text: "#_ #1_2 #122 #〃" - expected: [] - - - description: "Extract a hastag at the start" - text: "#hashtag here" - expected: ["hashtag"] - - - description: "Extract a hastag at the end" - text: "test a #hashtag" - expected: ["hashtag"] - - - description: "Extract a hastag in the middle" - text: "test a #hashtag in a string" - expected: ["hashtag"] - - - description: "Extract only a valid hashtag" - text: "#123 a #hashtag in a string" - expected: ["hashtag"] - - - description: "Extract a hashtag in a string of multi-byte characters" - text: "会議中 #hashtag 会議中" - expected: ["hashtag"] - - - description: "Extract multiple valid hashtags" - text: "One #two three #four" - expected: ["two", "four"] - - - description: "Extract a non-latin hashtag" - text: "Hashtags in #русский!" - expected: ["русский"] - - - description: "Extract multiple non-latin hashtags" - text: "Hashtags in #中文, #日本語, #한국말, and #русский! Try it out!" - expected: ["中文,", "日本語,", "한국말,", "русский"] diff --git a/vendor/golang.org/x/crypto/LICENSE b/vendor/golang.org/x/crypto/LICENSE deleted file mode 100644 index 6a66aea..0000000 --- a/vendor/golang.org/x/crypto/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -Copyright (c) 2009 The Go Authors. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of Google Inc. nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/golang.org/x/crypto/PATENTS b/vendor/golang.org/x/crypto/PATENTS deleted file mode 100644 index 7330990..0000000 --- a/vendor/golang.org/x/crypto/PATENTS +++ /dev/null @@ -1,22 +0,0 @@ -Additional IP Rights Grant (Patents) - -"This implementation" means the copyrightable works distributed by -Google as part of the Go project. - -Google 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, -transfer and otherwise run, modify and propagate the contents of this -implementation of Go, where such license applies only to those patent -claims, both currently owned or controlled by Google and acquired in -the future, licensable by Google that are necessarily infringed by this -implementation of Go. This grant does not include claims that would be -infringed only as a consequence of further modification of this -implementation. If you or your agent or exclusive licensee institute or -order or agree to the institution of patent litigation against any -entity (including a cross-claim or counterclaim in a lawsuit) alleging -that this implementation of Go or any code incorporated within this -implementation of Go constitutes direct or contributory patent -infringement, or inducement of patent infringement, then any patent -rights granted to you under this License for this implementation of Go -shall terminate as of the date such litigation is filed. diff --git a/vendor/golang.org/x/crypto/curve25519/const_amd64.s b/vendor/golang.org/x/crypto/curve25519/const_amd64.s deleted file mode 100644 index 797f9b0..0000000 --- a/vendor/golang.org/x/crypto/curve25519/const_amd64.s +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright 2012 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. - -// This code was translated into a form compatible with 6a from the public -// domain sources in SUPERCOP: http://bench.cr.yp.to/supercop.html - -// +build amd64,!gccgo,!appengine - -DATA ·REDMASK51(SB)/8, $0x0007FFFFFFFFFFFF -GLOBL ·REDMASK51(SB), 8, $8 - -DATA ·_121666_213(SB)/8, $996687872 -GLOBL ·_121666_213(SB), 8, $8 - -DATA ·_2P0(SB)/8, $0xFFFFFFFFFFFDA -GLOBL ·_2P0(SB), 8, $8 - -DATA ·_2P1234(SB)/8, $0xFFFFFFFFFFFFE -GLOBL ·_2P1234(SB), 8, $8 diff --git a/vendor/golang.org/x/crypto/curve25519/cswap_amd64.s b/vendor/golang.org/x/crypto/curve25519/cswap_amd64.s deleted file mode 100644 index 45484d1..0000000 --- a/vendor/golang.org/x/crypto/curve25519/cswap_amd64.s +++ /dev/null @@ -1,88 +0,0 @@ -// Copyright 2012 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. - -// This code was translated into a form compatible with 6a from the public -// domain sources in SUPERCOP: http://bench.cr.yp.to/supercop.html - -// +build amd64,!gccgo,!appengine - -// func cswap(inout *[5]uint64, v uint64) -TEXT ·cswap(SB),7,$0 - MOVQ inout+0(FP),DI - MOVQ v+8(FP),SI - - CMPQ SI,$1 - MOVQ 0(DI),SI - MOVQ 80(DI),DX - MOVQ 8(DI),CX - MOVQ 88(DI),R8 - MOVQ SI,R9 - CMOVQEQ DX,SI - CMOVQEQ R9,DX - MOVQ CX,R9 - CMOVQEQ R8,CX - CMOVQEQ R9,R8 - MOVQ SI,0(DI) - MOVQ DX,80(DI) - MOVQ CX,8(DI) - MOVQ R8,88(DI) - MOVQ 16(DI),SI - MOVQ 96(DI),DX - MOVQ 24(DI),CX - MOVQ 104(DI),R8 - MOVQ SI,R9 - CMOVQEQ DX,SI - CMOVQEQ R9,DX - MOVQ CX,R9 - CMOVQEQ R8,CX - CMOVQEQ R9,R8 - MOVQ SI,16(DI) - MOVQ DX,96(DI) - MOVQ CX,24(DI) - MOVQ R8,104(DI) - MOVQ 32(DI),SI - MOVQ 112(DI),DX - MOVQ 40(DI),CX - MOVQ 120(DI),R8 - MOVQ SI,R9 - CMOVQEQ DX,SI - CMOVQEQ R9,DX - MOVQ CX,R9 - CMOVQEQ R8,CX - CMOVQEQ R9,R8 - MOVQ SI,32(DI) - MOVQ DX,112(DI) - MOVQ CX,40(DI) - MOVQ R8,120(DI) - MOVQ 48(DI),SI - MOVQ 128(DI),DX - MOVQ 56(DI),CX - MOVQ 136(DI),R8 - MOVQ SI,R9 - CMOVQEQ DX,SI - CMOVQEQ R9,DX - MOVQ CX,R9 - CMOVQEQ R8,CX - CMOVQEQ R9,R8 - MOVQ SI,48(DI) - MOVQ DX,128(DI) - MOVQ CX,56(DI) - MOVQ R8,136(DI) - MOVQ 64(DI),SI - MOVQ 144(DI),DX - MOVQ 72(DI),CX - MOVQ 152(DI),R8 - MOVQ SI,R9 - CMOVQEQ DX,SI - CMOVQEQ R9,DX - MOVQ CX,R9 - CMOVQEQ R8,CX - CMOVQEQ R9,R8 - MOVQ SI,64(DI) - MOVQ DX,144(DI) - MOVQ CX,72(DI) - MOVQ R8,152(DI) - MOVQ DI,AX - MOVQ SI,DX - RET diff --git a/vendor/golang.org/x/crypto/curve25519/curve25519.go b/vendor/golang.org/x/crypto/curve25519/curve25519.go deleted file mode 100644 index 6918c47..0000000 --- a/vendor/golang.org/x/crypto/curve25519/curve25519.go +++ /dev/null @@ -1,841 +0,0 @@ -// Copyright 2013 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. - -// We have a implementation in amd64 assembly so this code is only run on -// non-amd64 platforms. The amd64 assembly does not support gccgo. -// +build !amd64 gccgo appengine - -package curve25519 - -// This code is a port of the public domain, "ref10" implementation of -// curve25519 from SUPERCOP 20130419 by D. J. Bernstein. - -// fieldElement represents an element of the field GF(2^255 - 19). An element -// t, entries t[0]...t[9], represents the integer t[0]+2^26 t[1]+2^51 t[2]+2^77 -// t[3]+2^102 t[4]+...+2^230 t[9]. Bounds on each t[i] vary depending on -// context. -type fieldElement [10]int32 - -func feZero(fe *fieldElement) { - for i := range fe { - fe[i] = 0 - } -} - -func feOne(fe *fieldElement) { - feZero(fe) - fe[0] = 1 -} - -func feAdd(dst, a, b *fieldElement) { - for i := range dst { - dst[i] = a[i] + b[i] - } -} - -func feSub(dst, a, b *fieldElement) { - for i := range dst { - dst[i] = a[i] - b[i] - } -} - -func feCopy(dst, src *fieldElement) { - for i := range dst { - dst[i] = src[i] - } -} - -// feCSwap replaces (f,g) with (g,f) if b == 1; replaces (f,g) with (f,g) if b == 0. -// -// Preconditions: b in {0,1}. -func feCSwap(f, g *fieldElement, b int32) { - var x fieldElement - b = -b - for i := range x { - x[i] = b & (f[i] ^ g[i]) - } - - for i := range f { - f[i] ^= x[i] - } - for i := range g { - g[i] ^= x[i] - } -} - -// load3 reads a 24-bit, little-endian value from in. -func load3(in []byte) int64 { - var r int64 - r = int64(in[0]) - r |= int64(in[1]) << 8 - r |= int64(in[2]) << 16 - return r -} - -// load4 reads a 32-bit, little-endian value from in. -func load4(in []byte) int64 { - var r int64 - r = int64(in[0]) - r |= int64(in[1]) << 8 - r |= int64(in[2]) << 16 - r |= int64(in[3]) << 24 - return r -} - -func feFromBytes(dst *fieldElement, src *[32]byte) { - h0 := load4(src[:]) - h1 := load3(src[4:]) << 6 - h2 := load3(src[7:]) << 5 - h3 := load3(src[10:]) << 3 - h4 := load3(src[13:]) << 2 - h5 := load4(src[16:]) - h6 := load3(src[20:]) << 7 - h7 := load3(src[23:]) << 5 - h8 := load3(src[26:]) << 4 - h9 := load3(src[29:]) << 2 - - var carry [10]int64 - carry[9] = (h9 + 1<<24) >> 25 - h0 += carry[9] * 19 - h9 -= carry[9] << 25 - carry[1] = (h1 + 1<<24) >> 25 - h2 += carry[1] - h1 -= carry[1] << 25 - carry[3] = (h3 + 1<<24) >> 25 - h4 += carry[3] - h3 -= carry[3] << 25 - carry[5] = (h5 + 1<<24) >> 25 - h6 += carry[5] - h5 -= carry[5] << 25 - carry[7] = (h7 + 1<<24) >> 25 - h8 += carry[7] - h7 -= carry[7] << 25 - - carry[0] = (h0 + 1<<25) >> 26 - h1 += carry[0] - h0 -= carry[0] << 26 - carry[2] = (h2 + 1<<25) >> 26 - h3 += carry[2] - h2 -= carry[2] << 26 - carry[4] = (h4 + 1<<25) >> 26 - h5 += carry[4] - h4 -= carry[4] << 26 - carry[6] = (h6 + 1<<25) >> 26 - h7 += carry[6] - h6 -= carry[6] << 26 - carry[8] = (h8 + 1<<25) >> 26 - h9 += carry[8] - h8 -= carry[8] << 26 - - dst[0] = int32(h0) - dst[1] = int32(h1) - dst[2] = int32(h2) - dst[3] = int32(h3) - dst[4] = int32(h4) - dst[5] = int32(h5) - dst[6] = int32(h6) - dst[7] = int32(h7) - dst[8] = int32(h8) - dst[9] = int32(h9) -} - -// feToBytes marshals h to s. -// Preconditions: -// |h| bounded by 1.1*2^25,1.1*2^24,1.1*2^25,1.1*2^24,etc. -// -// Write p=2^255-19; q=floor(h/p). -// Basic claim: q = floor(2^(-255)(h + 19 2^(-25)h9 + 2^(-1))). -// -// Proof: -// Have |h|<=p so |q|<=1 so |19^2 2^(-255) q|<1/4. -// Also have |h-2^230 h9|<2^230 so |19 2^(-255)(h-2^230 h9)|<1/4. -// -// Write y=2^(-1)-19^2 2^(-255)q-19 2^(-255)(h-2^230 h9). -// Then 0> 25 - q = (h[0] + q) >> 26 - q = (h[1] + q) >> 25 - q = (h[2] + q) >> 26 - q = (h[3] + q) >> 25 - q = (h[4] + q) >> 26 - q = (h[5] + q) >> 25 - q = (h[6] + q) >> 26 - q = (h[7] + q) >> 25 - q = (h[8] + q) >> 26 - q = (h[9] + q) >> 25 - - // Goal: Output h-(2^255-19)q, which is between 0 and 2^255-20. - h[0] += 19 * q - // Goal: Output h-2^255 q, which is between 0 and 2^255-20. - - carry[0] = h[0] >> 26 - h[1] += carry[0] - h[0] -= carry[0] << 26 - carry[1] = h[1] >> 25 - h[2] += carry[1] - h[1] -= carry[1] << 25 - carry[2] = h[2] >> 26 - h[3] += carry[2] - h[2] -= carry[2] << 26 - carry[3] = h[3] >> 25 - h[4] += carry[3] - h[3] -= carry[3] << 25 - carry[4] = h[4] >> 26 - h[5] += carry[4] - h[4] -= carry[4] << 26 - carry[5] = h[5] >> 25 - h[6] += carry[5] - h[5] -= carry[5] << 25 - carry[6] = h[6] >> 26 - h[7] += carry[6] - h[6] -= carry[6] << 26 - carry[7] = h[7] >> 25 - h[8] += carry[7] - h[7] -= carry[7] << 25 - carry[8] = h[8] >> 26 - h[9] += carry[8] - h[8] -= carry[8] << 26 - carry[9] = h[9] >> 25 - h[9] -= carry[9] << 25 - // h10 = carry9 - - // Goal: Output h[0]+...+2^255 h10-2^255 q, which is between 0 and 2^255-20. - // Have h[0]+...+2^230 h[9] between 0 and 2^255-1; - // evidently 2^255 h10-2^255 q = 0. - // Goal: Output h[0]+...+2^230 h[9]. - - s[0] = byte(h[0] >> 0) - s[1] = byte(h[0] >> 8) - s[2] = byte(h[0] >> 16) - s[3] = byte((h[0] >> 24) | (h[1] << 2)) - s[4] = byte(h[1] >> 6) - s[5] = byte(h[1] >> 14) - s[6] = byte((h[1] >> 22) | (h[2] << 3)) - s[7] = byte(h[2] >> 5) - s[8] = byte(h[2] >> 13) - s[9] = byte((h[2] >> 21) | (h[3] << 5)) - s[10] = byte(h[3] >> 3) - s[11] = byte(h[3] >> 11) - s[12] = byte((h[3] >> 19) | (h[4] << 6)) - s[13] = byte(h[4] >> 2) - s[14] = byte(h[4] >> 10) - s[15] = byte(h[4] >> 18) - s[16] = byte(h[5] >> 0) - s[17] = byte(h[5] >> 8) - s[18] = byte(h[5] >> 16) - s[19] = byte((h[5] >> 24) | (h[6] << 1)) - s[20] = byte(h[6] >> 7) - s[21] = byte(h[6] >> 15) - s[22] = byte((h[6] >> 23) | (h[7] << 3)) - s[23] = byte(h[7] >> 5) - s[24] = byte(h[7] >> 13) - s[25] = byte((h[7] >> 21) | (h[8] << 4)) - s[26] = byte(h[8] >> 4) - s[27] = byte(h[8] >> 12) - s[28] = byte((h[8] >> 20) | (h[9] << 6)) - s[29] = byte(h[9] >> 2) - s[30] = byte(h[9] >> 10) - s[31] = byte(h[9] >> 18) -} - -// feMul calculates h = f * g -// Can overlap h with f or g. -// -// Preconditions: -// |f| bounded by 1.1*2^26,1.1*2^25,1.1*2^26,1.1*2^25,etc. -// |g| bounded by 1.1*2^26,1.1*2^25,1.1*2^26,1.1*2^25,etc. -// -// Postconditions: -// |h| bounded by 1.1*2^25,1.1*2^24,1.1*2^25,1.1*2^24,etc. -// -// Notes on implementation strategy: -// -// Using schoolbook multiplication. -// Karatsuba would save a little in some cost models. -// -// Most multiplications by 2 and 19 are 32-bit precomputations; -// cheaper than 64-bit postcomputations. -// -// There is one remaining multiplication by 19 in the carry chain; -// one *19 precomputation can be merged into this, -// but the resulting data flow is considerably less clean. -// -// There are 12 carries below. -// 10 of them are 2-way parallelizable and vectorizable. -// Can get away with 11 carries, but then data flow is much deeper. -// -// With tighter constraints on inputs can squeeze carries into int32. -func feMul(h, f, g *fieldElement) { - f0 := f[0] - f1 := f[1] - f2 := f[2] - f3 := f[3] - f4 := f[4] - f5 := f[5] - f6 := f[6] - f7 := f[7] - f8 := f[8] - f9 := f[9] - g0 := g[0] - g1 := g[1] - g2 := g[2] - g3 := g[3] - g4 := g[4] - g5 := g[5] - g6 := g[6] - g7 := g[7] - g8 := g[8] - g9 := g[9] - g1_19 := 19 * g1 // 1.4*2^29 - g2_19 := 19 * g2 // 1.4*2^30; still ok - g3_19 := 19 * g3 - g4_19 := 19 * g4 - g5_19 := 19 * g5 - g6_19 := 19 * g6 - g7_19 := 19 * g7 - g8_19 := 19 * g8 - g9_19 := 19 * g9 - f1_2 := 2 * f1 - f3_2 := 2 * f3 - f5_2 := 2 * f5 - f7_2 := 2 * f7 - f9_2 := 2 * f9 - f0g0 := int64(f0) * int64(g0) - f0g1 := int64(f0) * int64(g1) - f0g2 := int64(f0) * int64(g2) - f0g3 := int64(f0) * int64(g3) - f0g4 := int64(f0) * int64(g4) - f0g5 := int64(f0) * int64(g5) - f0g6 := int64(f0) * int64(g6) - f0g7 := int64(f0) * int64(g7) - f0g8 := int64(f0) * int64(g8) - f0g9 := int64(f0) * int64(g9) - f1g0 := int64(f1) * int64(g0) - f1g1_2 := int64(f1_2) * int64(g1) - f1g2 := int64(f1) * int64(g2) - f1g3_2 := int64(f1_2) * int64(g3) - f1g4 := int64(f1) * int64(g4) - f1g5_2 := int64(f1_2) * int64(g5) - f1g6 := int64(f1) * int64(g6) - f1g7_2 := int64(f1_2) * int64(g7) - f1g8 := int64(f1) * int64(g8) - f1g9_38 := int64(f1_2) * int64(g9_19) - f2g0 := int64(f2) * int64(g0) - f2g1 := int64(f2) * int64(g1) - f2g2 := int64(f2) * int64(g2) - f2g3 := int64(f2) * int64(g3) - f2g4 := int64(f2) * int64(g4) - f2g5 := int64(f2) * int64(g5) - f2g6 := int64(f2) * int64(g6) - f2g7 := int64(f2) * int64(g7) - f2g8_19 := int64(f2) * int64(g8_19) - f2g9_19 := int64(f2) * int64(g9_19) - f3g0 := int64(f3) * int64(g0) - f3g1_2 := int64(f3_2) * int64(g1) - f3g2 := int64(f3) * int64(g2) - f3g3_2 := int64(f3_2) * int64(g3) - f3g4 := int64(f3) * int64(g4) - f3g5_2 := int64(f3_2) * int64(g5) - f3g6 := int64(f3) * int64(g6) - f3g7_38 := int64(f3_2) * int64(g7_19) - f3g8_19 := int64(f3) * int64(g8_19) - f3g9_38 := int64(f3_2) * int64(g9_19) - f4g0 := int64(f4) * int64(g0) - f4g1 := int64(f4) * int64(g1) - f4g2 := int64(f4) * int64(g2) - f4g3 := int64(f4) * int64(g3) - f4g4 := int64(f4) * int64(g4) - f4g5 := int64(f4) * int64(g5) - f4g6_19 := int64(f4) * int64(g6_19) - f4g7_19 := int64(f4) * int64(g7_19) - f4g8_19 := int64(f4) * int64(g8_19) - f4g9_19 := int64(f4) * int64(g9_19) - f5g0 := int64(f5) * int64(g0) - f5g1_2 := int64(f5_2) * int64(g1) - f5g2 := int64(f5) * int64(g2) - f5g3_2 := int64(f5_2) * int64(g3) - f5g4 := int64(f5) * int64(g4) - f5g5_38 := int64(f5_2) * int64(g5_19) - f5g6_19 := int64(f5) * int64(g6_19) - f5g7_38 := int64(f5_2) * int64(g7_19) - f5g8_19 := int64(f5) * int64(g8_19) - f5g9_38 := int64(f5_2) * int64(g9_19) - f6g0 := int64(f6) * int64(g0) - f6g1 := int64(f6) * int64(g1) - f6g2 := int64(f6) * int64(g2) - f6g3 := int64(f6) * int64(g3) - f6g4_19 := int64(f6) * int64(g4_19) - f6g5_19 := int64(f6) * int64(g5_19) - f6g6_19 := int64(f6) * int64(g6_19) - f6g7_19 := int64(f6) * int64(g7_19) - f6g8_19 := int64(f6) * int64(g8_19) - f6g9_19 := int64(f6) * int64(g9_19) - f7g0 := int64(f7) * int64(g0) - f7g1_2 := int64(f7_2) * int64(g1) - f7g2 := int64(f7) * int64(g2) - f7g3_38 := int64(f7_2) * int64(g3_19) - f7g4_19 := int64(f7) * int64(g4_19) - f7g5_38 := int64(f7_2) * int64(g5_19) - f7g6_19 := int64(f7) * int64(g6_19) - f7g7_38 := int64(f7_2) * int64(g7_19) - f7g8_19 := int64(f7) * int64(g8_19) - f7g9_38 := int64(f7_2) * int64(g9_19) - f8g0 := int64(f8) * int64(g0) - f8g1 := int64(f8) * int64(g1) - f8g2_19 := int64(f8) * int64(g2_19) - f8g3_19 := int64(f8) * int64(g3_19) - f8g4_19 := int64(f8) * int64(g4_19) - f8g5_19 := int64(f8) * int64(g5_19) - f8g6_19 := int64(f8) * int64(g6_19) - f8g7_19 := int64(f8) * int64(g7_19) - f8g8_19 := int64(f8) * int64(g8_19) - f8g9_19 := int64(f8) * int64(g9_19) - f9g0 := int64(f9) * int64(g0) - f9g1_38 := int64(f9_2) * int64(g1_19) - f9g2_19 := int64(f9) * int64(g2_19) - f9g3_38 := int64(f9_2) * int64(g3_19) - f9g4_19 := int64(f9) * int64(g4_19) - f9g5_38 := int64(f9_2) * int64(g5_19) - f9g6_19 := int64(f9) * int64(g6_19) - f9g7_38 := int64(f9_2) * int64(g7_19) - f9g8_19 := int64(f9) * int64(g8_19) - f9g9_38 := int64(f9_2) * int64(g9_19) - h0 := f0g0 + f1g9_38 + f2g8_19 + f3g7_38 + f4g6_19 + f5g5_38 + f6g4_19 + f7g3_38 + f8g2_19 + f9g1_38 - h1 := f0g1 + f1g0 + f2g9_19 + f3g8_19 + f4g7_19 + f5g6_19 + f6g5_19 + f7g4_19 + f8g3_19 + f9g2_19 - h2 := f0g2 + f1g1_2 + f2g0 + f3g9_38 + f4g8_19 + f5g7_38 + f6g6_19 + f7g5_38 + f8g4_19 + f9g3_38 - h3 := f0g3 + f1g2 + f2g1 + f3g0 + f4g9_19 + f5g8_19 + f6g7_19 + f7g6_19 + f8g5_19 + f9g4_19 - h4 := f0g4 + f1g3_2 + f2g2 + f3g1_2 + f4g0 + f5g9_38 + f6g8_19 + f7g7_38 + f8g6_19 + f9g5_38 - h5 := f0g5 + f1g4 + f2g3 + f3g2 + f4g1 + f5g0 + f6g9_19 + f7g8_19 + f8g7_19 + f9g6_19 - h6 := f0g6 + f1g5_2 + f2g4 + f3g3_2 + f4g2 + f5g1_2 + f6g0 + f7g9_38 + f8g8_19 + f9g7_38 - h7 := f0g7 + f1g6 + f2g5 + f3g4 + f4g3 + f5g2 + f6g1 + f7g0 + f8g9_19 + f9g8_19 - h8 := f0g8 + f1g7_2 + f2g6 + f3g5_2 + f4g4 + f5g3_2 + f6g2 + f7g1_2 + f8g0 + f9g9_38 - h9 := f0g9 + f1g8 + f2g7 + f3g6 + f4g5 + f5g4 + f6g3 + f7g2 + f8g1 + f9g0 - var carry [10]int64 - - // |h0| <= (1.1*1.1*2^52*(1+19+19+19+19)+1.1*1.1*2^50*(38+38+38+38+38)) - // i.e. |h0| <= 1.2*2^59; narrower ranges for h2, h4, h6, h8 - // |h1| <= (1.1*1.1*2^51*(1+1+19+19+19+19+19+19+19+19)) - // i.e. |h1| <= 1.5*2^58; narrower ranges for h3, h5, h7, h9 - - carry[0] = (h0 + (1 << 25)) >> 26 - h1 += carry[0] - h0 -= carry[0] << 26 - carry[4] = (h4 + (1 << 25)) >> 26 - h5 += carry[4] - h4 -= carry[4] << 26 - // |h0| <= 2^25 - // |h4| <= 2^25 - // |h1| <= 1.51*2^58 - // |h5| <= 1.51*2^58 - - carry[1] = (h1 + (1 << 24)) >> 25 - h2 += carry[1] - h1 -= carry[1] << 25 - carry[5] = (h5 + (1 << 24)) >> 25 - h6 += carry[5] - h5 -= carry[5] << 25 - // |h1| <= 2^24; from now on fits into int32 - // |h5| <= 2^24; from now on fits into int32 - // |h2| <= 1.21*2^59 - // |h6| <= 1.21*2^59 - - carry[2] = (h2 + (1 << 25)) >> 26 - h3 += carry[2] - h2 -= carry[2] << 26 - carry[6] = (h6 + (1 << 25)) >> 26 - h7 += carry[6] - h6 -= carry[6] << 26 - // |h2| <= 2^25; from now on fits into int32 unchanged - // |h6| <= 2^25; from now on fits into int32 unchanged - // |h3| <= 1.51*2^58 - // |h7| <= 1.51*2^58 - - carry[3] = (h3 + (1 << 24)) >> 25 - h4 += carry[3] - h3 -= carry[3] << 25 - carry[7] = (h7 + (1 << 24)) >> 25 - h8 += carry[7] - h7 -= carry[7] << 25 - // |h3| <= 2^24; from now on fits into int32 unchanged - // |h7| <= 2^24; from now on fits into int32 unchanged - // |h4| <= 1.52*2^33 - // |h8| <= 1.52*2^33 - - carry[4] = (h4 + (1 << 25)) >> 26 - h5 += carry[4] - h4 -= carry[4] << 26 - carry[8] = (h8 + (1 << 25)) >> 26 - h9 += carry[8] - h8 -= carry[8] << 26 - // |h4| <= 2^25; from now on fits into int32 unchanged - // |h8| <= 2^25; from now on fits into int32 unchanged - // |h5| <= 1.01*2^24 - // |h9| <= 1.51*2^58 - - carry[9] = (h9 + (1 << 24)) >> 25 - h0 += carry[9] * 19 - h9 -= carry[9] << 25 - // |h9| <= 2^24; from now on fits into int32 unchanged - // |h0| <= 1.8*2^37 - - carry[0] = (h0 + (1 << 25)) >> 26 - h1 += carry[0] - h0 -= carry[0] << 26 - // |h0| <= 2^25; from now on fits into int32 unchanged - // |h1| <= 1.01*2^24 - - h[0] = int32(h0) - h[1] = int32(h1) - h[2] = int32(h2) - h[3] = int32(h3) - h[4] = int32(h4) - h[5] = int32(h5) - h[6] = int32(h6) - h[7] = int32(h7) - h[8] = int32(h8) - h[9] = int32(h9) -} - -// feSquare calculates h = f*f. Can overlap h with f. -// -// Preconditions: -// |f| bounded by 1.1*2^26,1.1*2^25,1.1*2^26,1.1*2^25,etc. -// -// Postconditions: -// |h| bounded by 1.1*2^25,1.1*2^24,1.1*2^25,1.1*2^24,etc. -func feSquare(h, f *fieldElement) { - f0 := f[0] - f1 := f[1] - f2 := f[2] - f3 := f[3] - f4 := f[4] - f5 := f[5] - f6 := f[6] - f7 := f[7] - f8 := f[8] - f9 := f[9] - f0_2 := 2 * f0 - f1_2 := 2 * f1 - f2_2 := 2 * f2 - f3_2 := 2 * f3 - f4_2 := 2 * f4 - f5_2 := 2 * f5 - f6_2 := 2 * f6 - f7_2 := 2 * f7 - f5_38 := 38 * f5 // 1.31*2^30 - f6_19 := 19 * f6 // 1.31*2^30 - f7_38 := 38 * f7 // 1.31*2^30 - f8_19 := 19 * f8 // 1.31*2^30 - f9_38 := 38 * f9 // 1.31*2^30 - f0f0 := int64(f0) * int64(f0) - f0f1_2 := int64(f0_2) * int64(f1) - f0f2_2 := int64(f0_2) * int64(f2) - f0f3_2 := int64(f0_2) * int64(f3) - f0f4_2 := int64(f0_2) * int64(f4) - f0f5_2 := int64(f0_2) * int64(f5) - f0f6_2 := int64(f0_2) * int64(f6) - f0f7_2 := int64(f0_2) * int64(f7) - f0f8_2 := int64(f0_2) * int64(f8) - f0f9_2 := int64(f0_2) * int64(f9) - f1f1_2 := int64(f1_2) * int64(f1) - f1f2_2 := int64(f1_2) * int64(f2) - f1f3_4 := int64(f1_2) * int64(f3_2) - f1f4_2 := int64(f1_2) * int64(f4) - f1f5_4 := int64(f1_2) * int64(f5_2) - f1f6_2 := int64(f1_2) * int64(f6) - f1f7_4 := int64(f1_2) * int64(f7_2) - f1f8_2 := int64(f1_2) * int64(f8) - f1f9_76 := int64(f1_2) * int64(f9_38) - f2f2 := int64(f2) * int64(f2) - f2f3_2 := int64(f2_2) * int64(f3) - f2f4_2 := int64(f2_2) * int64(f4) - f2f5_2 := int64(f2_2) * int64(f5) - f2f6_2 := int64(f2_2) * int64(f6) - f2f7_2 := int64(f2_2) * int64(f7) - f2f8_38 := int64(f2_2) * int64(f8_19) - f2f9_38 := int64(f2) * int64(f9_38) - f3f3_2 := int64(f3_2) * int64(f3) - f3f4_2 := int64(f3_2) * int64(f4) - f3f5_4 := int64(f3_2) * int64(f5_2) - f3f6_2 := int64(f3_2) * int64(f6) - f3f7_76 := int64(f3_2) * int64(f7_38) - f3f8_38 := int64(f3_2) * int64(f8_19) - f3f9_76 := int64(f3_2) * int64(f9_38) - f4f4 := int64(f4) * int64(f4) - f4f5_2 := int64(f4_2) * int64(f5) - f4f6_38 := int64(f4_2) * int64(f6_19) - f4f7_38 := int64(f4) * int64(f7_38) - f4f8_38 := int64(f4_2) * int64(f8_19) - f4f9_38 := int64(f4) * int64(f9_38) - f5f5_38 := int64(f5) * int64(f5_38) - f5f6_38 := int64(f5_2) * int64(f6_19) - f5f7_76 := int64(f5_2) * int64(f7_38) - f5f8_38 := int64(f5_2) * int64(f8_19) - f5f9_76 := int64(f5_2) * int64(f9_38) - f6f6_19 := int64(f6) * int64(f6_19) - f6f7_38 := int64(f6) * int64(f7_38) - f6f8_38 := int64(f6_2) * int64(f8_19) - f6f9_38 := int64(f6) * int64(f9_38) - f7f7_38 := int64(f7) * int64(f7_38) - f7f8_38 := int64(f7_2) * int64(f8_19) - f7f9_76 := int64(f7_2) * int64(f9_38) - f8f8_19 := int64(f8) * int64(f8_19) - f8f9_38 := int64(f8) * int64(f9_38) - f9f9_38 := int64(f9) * int64(f9_38) - h0 := f0f0 + f1f9_76 + f2f8_38 + f3f7_76 + f4f6_38 + f5f5_38 - h1 := f0f1_2 + f2f9_38 + f3f8_38 + f4f7_38 + f5f6_38 - h2 := f0f2_2 + f1f1_2 + f3f9_76 + f4f8_38 + f5f7_76 + f6f6_19 - h3 := f0f3_2 + f1f2_2 + f4f9_38 + f5f8_38 + f6f7_38 - h4 := f0f4_2 + f1f3_4 + f2f2 + f5f9_76 + f6f8_38 + f7f7_38 - h5 := f0f5_2 + f1f4_2 + f2f3_2 + f6f9_38 + f7f8_38 - h6 := f0f6_2 + f1f5_4 + f2f4_2 + f3f3_2 + f7f9_76 + f8f8_19 - h7 := f0f7_2 + f1f6_2 + f2f5_2 + f3f4_2 + f8f9_38 - h8 := f0f8_2 + f1f7_4 + f2f6_2 + f3f5_4 + f4f4 + f9f9_38 - h9 := f0f9_2 + f1f8_2 + f2f7_2 + f3f6_2 + f4f5_2 - var carry [10]int64 - - carry[0] = (h0 + (1 << 25)) >> 26 - h1 += carry[0] - h0 -= carry[0] << 26 - carry[4] = (h4 + (1 << 25)) >> 26 - h5 += carry[4] - h4 -= carry[4] << 26 - - carry[1] = (h1 + (1 << 24)) >> 25 - h2 += carry[1] - h1 -= carry[1] << 25 - carry[5] = (h5 + (1 << 24)) >> 25 - h6 += carry[5] - h5 -= carry[5] << 25 - - carry[2] = (h2 + (1 << 25)) >> 26 - h3 += carry[2] - h2 -= carry[2] << 26 - carry[6] = (h6 + (1 << 25)) >> 26 - h7 += carry[6] - h6 -= carry[6] << 26 - - carry[3] = (h3 + (1 << 24)) >> 25 - h4 += carry[3] - h3 -= carry[3] << 25 - carry[7] = (h7 + (1 << 24)) >> 25 - h8 += carry[7] - h7 -= carry[7] << 25 - - carry[4] = (h4 + (1 << 25)) >> 26 - h5 += carry[4] - h4 -= carry[4] << 26 - carry[8] = (h8 + (1 << 25)) >> 26 - h9 += carry[8] - h8 -= carry[8] << 26 - - carry[9] = (h9 + (1 << 24)) >> 25 - h0 += carry[9] * 19 - h9 -= carry[9] << 25 - - carry[0] = (h0 + (1 << 25)) >> 26 - h1 += carry[0] - h0 -= carry[0] << 26 - - h[0] = int32(h0) - h[1] = int32(h1) - h[2] = int32(h2) - h[3] = int32(h3) - h[4] = int32(h4) - h[5] = int32(h5) - h[6] = int32(h6) - h[7] = int32(h7) - h[8] = int32(h8) - h[9] = int32(h9) -} - -// feMul121666 calculates h = f * 121666. Can overlap h with f. -// -// Preconditions: -// |f| bounded by 1.1*2^26,1.1*2^25,1.1*2^26,1.1*2^25,etc. -// -// Postconditions: -// |h| bounded by 1.1*2^25,1.1*2^24,1.1*2^25,1.1*2^24,etc. -func feMul121666(h, f *fieldElement) { - h0 := int64(f[0]) * 121666 - h1 := int64(f[1]) * 121666 - h2 := int64(f[2]) * 121666 - h3 := int64(f[3]) * 121666 - h4 := int64(f[4]) * 121666 - h5 := int64(f[5]) * 121666 - h6 := int64(f[6]) * 121666 - h7 := int64(f[7]) * 121666 - h8 := int64(f[8]) * 121666 - h9 := int64(f[9]) * 121666 - var carry [10]int64 - - carry[9] = (h9 + (1 << 24)) >> 25 - h0 += carry[9] * 19 - h9 -= carry[9] << 25 - carry[1] = (h1 + (1 << 24)) >> 25 - h2 += carry[1] - h1 -= carry[1] << 25 - carry[3] = (h3 + (1 << 24)) >> 25 - h4 += carry[3] - h3 -= carry[3] << 25 - carry[5] = (h5 + (1 << 24)) >> 25 - h6 += carry[5] - h5 -= carry[5] << 25 - carry[7] = (h7 + (1 << 24)) >> 25 - h8 += carry[7] - h7 -= carry[7] << 25 - - carry[0] = (h0 + (1 << 25)) >> 26 - h1 += carry[0] - h0 -= carry[0] << 26 - carry[2] = (h2 + (1 << 25)) >> 26 - h3 += carry[2] - h2 -= carry[2] << 26 - carry[4] = (h4 + (1 << 25)) >> 26 - h5 += carry[4] - h4 -= carry[4] << 26 - carry[6] = (h6 + (1 << 25)) >> 26 - h7 += carry[6] - h6 -= carry[6] << 26 - carry[8] = (h8 + (1 << 25)) >> 26 - h9 += carry[8] - h8 -= carry[8] << 26 - - h[0] = int32(h0) - h[1] = int32(h1) - h[2] = int32(h2) - h[3] = int32(h3) - h[4] = int32(h4) - h[5] = int32(h5) - h[6] = int32(h6) - h[7] = int32(h7) - h[8] = int32(h8) - h[9] = int32(h9) -} - -// feInvert sets out = z^-1. -func feInvert(out, z *fieldElement) { - var t0, t1, t2, t3 fieldElement - var i int - - feSquare(&t0, z) - for i = 1; i < 1; i++ { - feSquare(&t0, &t0) - } - feSquare(&t1, &t0) - for i = 1; i < 2; i++ { - feSquare(&t1, &t1) - } - feMul(&t1, z, &t1) - feMul(&t0, &t0, &t1) - feSquare(&t2, &t0) - for i = 1; i < 1; i++ { - feSquare(&t2, &t2) - } - feMul(&t1, &t1, &t2) - feSquare(&t2, &t1) - for i = 1; i < 5; i++ { - feSquare(&t2, &t2) - } - feMul(&t1, &t2, &t1) - feSquare(&t2, &t1) - for i = 1; i < 10; i++ { - feSquare(&t2, &t2) - } - feMul(&t2, &t2, &t1) - feSquare(&t3, &t2) - for i = 1; i < 20; i++ { - feSquare(&t3, &t3) - } - feMul(&t2, &t3, &t2) - feSquare(&t2, &t2) - for i = 1; i < 10; i++ { - feSquare(&t2, &t2) - } - feMul(&t1, &t2, &t1) - feSquare(&t2, &t1) - for i = 1; i < 50; i++ { - feSquare(&t2, &t2) - } - feMul(&t2, &t2, &t1) - feSquare(&t3, &t2) - for i = 1; i < 100; i++ { - feSquare(&t3, &t3) - } - feMul(&t2, &t3, &t2) - feSquare(&t2, &t2) - for i = 1; i < 50; i++ { - feSquare(&t2, &t2) - } - feMul(&t1, &t2, &t1) - feSquare(&t1, &t1) - for i = 1; i < 5; i++ { - feSquare(&t1, &t1) - } - feMul(out, &t1, &t0) -} - -func scalarMult(out, in, base *[32]byte) { - var e [32]byte - - copy(e[:], in[:]) - e[0] &= 248 - e[31] &= 127 - e[31] |= 64 - - var x1, x2, z2, x3, z3, tmp0, tmp1 fieldElement - feFromBytes(&x1, base) - feOne(&x2) - feCopy(&x3, &x1) - feOne(&z3) - - swap := int32(0) - for pos := 254; pos >= 0; pos-- { - b := e[pos/8] >> uint(pos&7) - b &= 1 - swap ^= int32(b) - feCSwap(&x2, &x3, swap) - feCSwap(&z2, &z3, swap) - swap = int32(b) - - feSub(&tmp0, &x3, &z3) - feSub(&tmp1, &x2, &z2) - feAdd(&x2, &x2, &z2) - feAdd(&z2, &x3, &z3) - feMul(&z3, &tmp0, &x2) - feMul(&z2, &z2, &tmp1) - feSquare(&tmp0, &tmp1) - feSquare(&tmp1, &x2) - feAdd(&x3, &z3, &z2) - feSub(&z2, &z3, &z2) - feMul(&x2, &tmp1, &tmp0) - feSub(&tmp1, &tmp1, &tmp0) - feSquare(&z2, &z2) - feMul121666(&z3, &tmp1) - feSquare(&x3, &x3) - feAdd(&tmp0, &tmp0, &z3) - feMul(&z3, &x1, &z2) - feMul(&z2, &tmp1, &tmp0) - } - - feCSwap(&x2, &x3, swap) - feCSwap(&z2, &z3, swap) - - feInvert(&z2, &z2) - feMul(&x2, &x2, &z2) - feToBytes(out, &x2) -} diff --git a/vendor/golang.org/x/crypto/curve25519/doc.go b/vendor/golang.org/x/crypto/curve25519/doc.go deleted file mode 100644 index ebeea3c..0000000 --- a/vendor/golang.org/x/crypto/curve25519/doc.go +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright 2012 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 curve25519 provides an implementation of scalar multiplication on -// the elliptic curve known as curve25519. See http://cr.yp.to/ecdh.html -package curve25519 // import "golang.org/x/crypto/curve25519" - -// basePoint is the x coordinate of the generator of the curve. -var basePoint = [32]byte{9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} - -// ScalarMult sets dst to the product in*base where dst and base are the x -// coordinates of group points and all values are in little-endian form. -func ScalarMult(dst, in, base *[32]byte) { - scalarMult(dst, in, base) -} - -// ScalarBaseMult sets dst to the product in*base where dst and base are the x -// coordinates of group points, base is the standard generator and all values -// are in little-endian form. -func ScalarBaseMult(dst, in *[32]byte) { - ScalarMult(dst, in, &basePoint) -} diff --git a/vendor/golang.org/x/crypto/curve25519/freeze_amd64.s b/vendor/golang.org/x/crypto/curve25519/freeze_amd64.s deleted file mode 100644 index 37599fa..0000000 --- a/vendor/golang.org/x/crypto/curve25519/freeze_amd64.s +++ /dev/null @@ -1,94 +0,0 @@ -// Copyright 2012 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. - -// This code was translated into a form compatible with 6a from the public -// domain sources in SUPERCOP: http://bench.cr.yp.to/supercop.html - -// +build amd64,!gccgo,!appengine - -// func freeze(inout *[5]uint64) -TEXT ·freeze(SB),7,$96-8 - MOVQ inout+0(FP), DI - - MOVQ SP,R11 - MOVQ $31,CX - NOTQ CX - ANDQ CX,SP - ADDQ $32,SP - - MOVQ R11,0(SP) - MOVQ R12,8(SP) - MOVQ R13,16(SP) - MOVQ R14,24(SP) - MOVQ R15,32(SP) - MOVQ BX,40(SP) - MOVQ BP,48(SP) - MOVQ 0(DI),SI - MOVQ 8(DI),DX - MOVQ 16(DI),CX - MOVQ 24(DI),R8 - MOVQ 32(DI),R9 - MOVQ ·REDMASK51(SB),AX - MOVQ AX,R10 - SUBQ $18,R10 - MOVQ $3,R11 -REDUCELOOP: - MOVQ SI,R12 - SHRQ $51,R12 - ANDQ AX,SI - ADDQ R12,DX - MOVQ DX,R12 - SHRQ $51,R12 - ANDQ AX,DX - ADDQ R12,CX - MOVQ CX,R12 - SHRQ $51,R12 - ANDQ AX,CX - ADDQ R12,R8 - MOVQ R8,R12 - SHRQ $51,R12 - ANDQ AX,R8 - ADDQ R12,R9 - MOVQ R9,R12 - SHRQ $51,R12 - ANDQ AX,R9 - IMUL3Q $19,R12,R12 - ADDQ R12,SI - SUBQ $1,R11 - JA REDUCELOOP - MOVQ $1,R12 - CMPQ R10,SI - CMOVQLT R11,R12 - CMPQ AX,DX - CMOVQNE R11,R12 - CMPQ AX,CX - CMOVQNE R11,R12 - CMPQ AX,R8 - CMOVQNE R11,R12 - CMPQ AX,R9 - CMOVQNE R11,R12 - NEGQ R12 - ANDQ R12,AX - ANDQ R12,R10 - SUBQ R10,SI - SUBQ AX,DX - SUBQ AX,CX - SUBQ AX,R8 - SUBQ AX,R9 - MOVQ SI,0(DI) - MOVQ DX,8(DI) - MOVQ CX,16(DI) - MOVQ R8,24(DI) - MOVQ R9,32(DI) - MOVQ 0(SP),R11 - MOVQ 8(SP),R12 - MOVQ 16(SP),R13 - MOVQ 24(SP),R14 - MOVQ 32(SP),R15 - MOVQ 40(SP),BX - MOVQ 48(SP),BP - MOVQ R11,SP - MOVQ DI,AX - MOVQ SI,DX - RET diff --git a/vendor/golang.org/x/crypto/curve25519/ladderstep_amd64.s b/vendor/golang.org/x/crypto/curve25519/ladderstep_amd64.s deleted file mode 100644 index 3949f9c..0000000 --- a/vendor/golang.org/x/crypto/curve25519/ladderstep_amd64.s +++ /dev/null @@ -1,1398 +0,0 @@ -// Copyright 2012 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. - -// This code was translated into a form compatible with 6a from the public -// domain sources in SUPERCOP: http://bench.cr.yp.to/supercop.html - -// +build amd64,!gccgo,!appengine - -// func ladderstep(inout *[5][5]uint64) -TEXT ·ladderstep(SB),0,$384-8 - MOVQ inout+0(FP),DI - - MOVQ SP,R11 - MOVQ $31,CX - NOTQ CX - ANDQ CX,SP - ADDQ $32,SP - - MOVQ R11,0(SP) - MOVQ R12,8(SP) - MOVQ R13,16(SP) - MOVQ R14,24(SP) - MOVQ R15,32(SP) - MOVQ BX,40(SP) - MOVQ BP,48(SP) - MOVQ 40(DI),SI - MOVQ 48(DI),DX - MOVQ 56(DI),CX - MOVQ 64(DI),R8 - MOVQ 72(DI),R9 - MOVQ SI,AX - MOVQ DX,R10 - MOVQ CX,R11 - MOVQ R8,R12 - MOVQ R9,R13 - ADDQ ·_2P0(SB),AX - ADDQ ·_2P1234(SB),R10 - ADDQ ·_2P1234(SB),R11 - ADDQ ·_2P1234(SB),R12 - ADDQ ·_2P1234(SB),R13 - ADDQ 80(DI),SI - ADDQ 88(DI),DX - ADDQ 96(DI),CX - ADDQ 104(DI),R8 - ADDQ 112(DI),R9 - SUBQ 80(DI),AX - SUBQ 88(DI),R10 - SUBQ 96(DI),R11 - SUBQ 104(DI),R12 - SUBQ 112(DI),R13 - MOVQ SI,56(SP) - MOVQ DX,64(SP) - MOVQ CX,72(SP) - MOVQ R8,80(SP) - MOVQ R9,88(SP) - MOVQ AX,96(SP) - MOVQ R10,104(SP) - MOVQ R11,112(SP) - MOVQ R12,120(SP) - MOVQ R13,128(SP) - MOVQ 96(SP),AX - MULQ 96(SP) - MOVQ AX,SI - MOVQ DX,CX - MOVQ 96(SP),AX - SHLQ $1,AX - MULQ 104(SP) - MOVQ AX,R8 - MOVQ DX,R9 - MOVQ 96(SP),AX - SHLQ $1,AX - MULQ 112(SP) - MOVQ AX,R10 - MOVQ DX,R11 - MOVQ 96(SP),AX - SHLQ $1,AX - MULQ 120(SP) - MOVQ AX,R12 - MOVQ DX,R13 - MOVQ 96(SP),AX - SHLQ $1,AX - MULQ 128(SP) - MOVQ AX,R14 - MOVQ DX,R15 - MOVQ 104(SP),AX - MULQ 104(SP) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 104(SP),AX - SHLQ $1,AX - MULQ 112(SP) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ 104(SP),AX - SHLQ $1,AX - MULQ 120(SP) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 104(SP),DX - IMUL3Q $38,DX,AX - MULQ 128(SP) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 112(SP),AX - MULQ 112(SP) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 112(SP),DX - IMUL3Q $38,DX,AX - MULQ 120(SP) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 112(SP),DX - IMUL3Q $38,DX,AX - MULQ 128(SP) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 120(SP),DX - IMUL3Q $19,DX,AX - MULQ 120(SP) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 120(SP),DX - IMUL3Q $38,DX,AX - MULQ 128(SP) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 128(SP),DX - IMUL3Q $19,DX,AX - MULQ 128(SP) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ ·REDMASK51(SB),DX - SHLQ $13,CX:SI - ANDQ DX,SI - SHLQ $13,R9:R8 - ANDQ DX,R8 - ADDQ CX,R8 - SHLQ $13,R11:R10 - ANDQ DX,R10 - ADDQ R9,R10 - SHLQ $13,R13:R12 - ANDQ DX,R12 - ADDQ R11,R12 - SHLQ $13,R15:R14 - ANDQ DX,R14 - ADDQ R13,R14 - IMUL3Q $19,R15,CX - ADDQ CX,SI - MOVQ SI,CX - SHRQ $51,CX - ADDQ R8,CX - ANDQ DX,SI - MOVQ CX,R8 - SHRQ $51,CX - ADDQ R10,CX - ANDQ DX,R8 - MOVQ CX,R9 - SHRQ $51,CX - ADDQ R12,CX - ANDQ DX,R9 - MOVQ CX,AX - SHRQ $51,CX - ADDQ R14,CX - ANDQ DX,AX - MOVQ CX,R10 - SHRQ $51,CX - IMUL3Q $19,CX,CX - ADDQ CX,SI - ANDQ DX,R10 - MOVQ SI,136(SP) - MOVQ R8,144(SP) - MOVQ R9,152(SP) - MOVQ AX,160(SP) - MOVQ R10,168(SP) - MOVQ 56(SP),AX - MULQ 56(SP) - MOVQ AX,SI - MOVQ DX,CX - MOVQ 56(SP),AX - SHLQ $1,AX - MULQ 64(SP) - MOVQ AX,R8 - MOVQ DX,R9 - MOVQ 56(SP),AX - SHLQ $1,AX - MULQ 72(SP) - MOVQ AX,R10 - MOVQ DX,R11 - MOVQ 56(SP),AX - SHLQ $1,AX - MULQ 80(SP) - MOVQ AX,R12 - MOVQ DX,R13 - MOVQ 56(SP),AX - SHLQ $1,AX - MULQ 88(SP) - MOVQ AX,R14 - MOVQ DX,R15 - MOVQ 64(SP),AX - MULQ 64(SP) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 64(SP),AX - SHLQ $1,AX - MULQ 72(SP) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ 64(SP),AX - SHLQ $1,AX - MULQ 80(SP) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 64(SP),DX - IMUL3Q $38,DX,AX - MULQ 88(SP) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 72(SP),AX - MULQ 72(SP) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 72(SP),DX - IMUL3Q $38,DX,AX - MULQ 80(SP) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 72(SP),DX - IMUL3Q $38,DX,AX - MULQ 88(SP) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 80(SP),DX - IMUL3Q $19,DX,AX - MULQ 80(SP) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 80(SP),DX - IMUL3Q $38,DX,AX - MULQ 88(SP) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 88(SP),DX - IMUL3Q $19,DX,AX - MULQ 88(SP) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ ·REDMASK51(SB),DX - SHLQ $13,CX:SI - ANDQ DX,SI - SHLQ $13,R9:R8 - ANDQ DX,R8 - ADDQ CX,R8 - SHLQ $13,R11:R10 - ANDQ DX,R10 - ADDQ R9,R10 - SHLQ $13,R13:R12 - ANDQ DX,R12 - ADDQ R11,R12 - SHLQ $13,R15:R14 - ANDQ DX,R14 - ADDQ R13,R14 - IMUL3Q $19,R15,CX - ADDQ CX,SI - MOVQ SI,CX - SHRQ $51,CX - ADDQ R8,CX - ANDQ DX,SI - MOVQ CX,R8 - SHRQ $51,CX - ADDQ R10,CX - ANDQ DX,R8 - MOVQ CX,R9 - SHRQ $51,CX - ADDQ R12,CX - ANDQ DX,R9 - MOVQ CX,AX - SHRQ $51,CX - ADDQ R14,CX - ANDQ DX,AX - MOVQ CX,R10 - SHRQ $51,CX - IMUL3Q $19,CX,CX - ADDQ CX,SI - ANDQ DX,R10 - MOVQ SI,176(SP) - MOVQ R8,184(SP) - MOVQ R9,192(SP) - MOVQ AX,200(SP) - MOVQ R10,208(SP) - MOVQ SI,SI - MOVQ R8,DX - MOVQ R9,CX - MOVQ AX,R8 - MOVQ R10,R9 - ADDQ ·_2P0(SB),SI - ADDQ ·_2P1234(SB),DX - ADDQ ·_2P1234(SB),CX - ADDQ ·_2P1234(SB),R8 - ADDQ ·_2P1234(SB),R9 - SUBQ 136(SP),SI - SUBQ 144(SP),DX - SUBQ 152(SP),CX - SUBQ 160(SP),R8 - SUBQ 168(SP),R9 - MOVQ SI,216(SP) - MOVQ DX,224(SP) - MOVQ CX,232(SP) - MOVQ R8,240(SP) - MOVQ R9,248(SP) - MOVQ 120(DI),SI - MOVQ 128(DI),DX - MOVQ 136(DI),CX - MOVQ 144(DI),R8 - MOVQ 152(DI),R9 - MOVQ SI,AX - MOVQ DX,R10 - MOVQ CX,R11 - MOVQ R8,R12 - MOVQ R9,R13 - ADDQ ·_2P0(SB),AX - ADDQ ·_2P1234(SB),R10 - ADDQ ·_2P1234(SB),R11 - ADDQ ·_2P1234(SB),R12 - ADDQ ·_2P1234(SB),R13 - ADDQ 160(DI),SI - ADDQ 168(DI),DX - ADDQ 176(DI),CX - ADDQ 184(DI),R8 - ADDQ 192(DI),R9 - SUBQ 160(DI),AX - SUBQ 168(DI),R10 - SUBQ 176(DI),R11 - SUBQ 184(DI),R12 - SUBQ 192(DI),R13 - MOVQ SI,256(SP) - MOVQ DX,264(SP) - MOVQ CX,272(SP) - MOVQ R8,280(SP) - MOVQ R9,288(SP) - MOVQ AX,296(SP) - MOVQ R10,304(SP) - MOVQ R11,312(SP) - MOVQ R12,320(SP) - MOVQ R13,328(SP) - MOVQ 280(SP),SI - IMUL3Q $19,SI,AX - MOVQ AX,336(SP) - MULQ 112(SP) - MOVQ AX,SI - MOVQ DX,CX - MOVQ 288(SP),DX - IMUL3Q $19,DX,AX - MOVQ AX,344(SP) - MULQ 104(SP) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 256(SP),AX - MULQ 96(SP) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 256(SP),AX - MULQ 104(SP) - MOVQ AX,R8 - MOVQ DX,R9 - MOVQ 256(SP),AX - MULQ 112(SP) - MOVQ AX,R10 - MOVQ DX,R11 - MOVQ 256(SP),AX - MULQ 120(SP) - MOVQ AX,R12 - MOVQ DX,R13 - MOVQ 256(SP),AX - MULQ 128(SP) - MOVQ AX,R14 - MOVQ DX,R15 - MOVQ 264(SP),AX - MULQ 96(SP) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 264(SP),AX - MULQ 104(SP) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 264(SP),AX - MULQ 112(SP) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ 264(SP),AX - MULQ 120(SP) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 264(SP),DX - IMUL3Q $19,DX,AX - MULQ 128(SP) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 272(SP),AX - MULQ 96(SP) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 272(SP),AX - MULQ 104(SP) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ 272(SP),AX - MULQ 112(SP) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 272(SP),DX - IMUL3Q $19,DX,AX - MULQ 120(SP) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 272(SP),DX - IMUL3Q $19,DX,AX - MULQ 128(SP) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 280(SP),AX - MULQ 96(SP) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ 280(SP),AX - MULQ 104(SP) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 336(SP),AX - MULQ 120(SP) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 336(SP),AX - MULQ 128(SP) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 288(SP),AX - MULQ 96(SP) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 344(SP),AX - MULQ 112(SP) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 344(SP),AX - MULQ 120(SP) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 344(SP),AX - MULQ 128(SP) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ ·REDMASK51(SB),DX - SHLQ $13,CX:SI - ANDQ DX,SI - SHLQ $13,R9:R8 - ANDQ DX,R8 - ADDQ CX,R8 - SHLQ $13,R11:R10 - ANDQ DX,R10 - ADDQ R9,R10 - SHLQ $13,R13:R12 - ANDQ DX,R12 - ADDQ R11,R12 - SHLQ $13,R15:R14 - ANDQ DX,R14 - ADDQ R13,R14 - IMUL3Q $19,R15,CX - ADDQ CX,SI - MOVQ SI,CX - SHRQ $51,CX - ADDQ R8,CX - MOVQ CX,R8 - SHRQ $51,CX - ANDQ DX,SI - ADDQ R10,CX - MOVQ CX,R9 - SHRQ $51,CX - ANDQ DX,R8 - ADDQ R12,CX - MOVQ CX,AX - SHRQ $51,CX - ANDQ DX,R9 - ADDQ R14,CX - MOVQ CX,R10 - SHRQ $51,CX - ANDQ DX,AX - IMUL3Q $19,CX,CX - ADDQ CX,SI - ANDQ DX,R10 - MOVQ SI,96(SP) - MOVQ R8,104(SP) - MOVQ R9,112(SP) - MOVQ AX,120(SP) - MOVQ R10,128(SP) - MOVQ 320(SP),SI - IMUL3Q $19,SI,AX - MOVQ AX,256(SP) - MULQ 72(SP) - MOVQ AX,SI - MOVQ DX,CX - MOVQ 328(SP),DX - IMUL3Q $19,DX,AX - MOVQ AX,264(SP) - MULQ 64(SP) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 296(SP),AX - MULQ 56(SP) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 296(SP),AX - MULQ 64(SP) - MOVQ AX,R8 - MOVQ DX,R9 - MOVQ 296(SP),AX - MULQ 72(SP) - MOVQ AX,R10 - MOVQ DX,R11 - MOVQ 296(SP),AX - MULQ 80(SP) - MOVQ AX,R12 - MOVQ DX,R13 - MOVQ 296(SP),AX - MULQ 88(SP) - MOVQ AX,R14 - MOVQ DX,R15 - MOVQ 304(SP),AX - MULQ 56(SP) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 304(SP),AX - MULQ 64(SP) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 304(SP),AX - MULQ 72(SP) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ 304(SP),AX - MULQ 80(SP) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 304(SP),DX - IMUL3Q $19,DX,AX - MULQ 88(SP) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 312(SP),AX - MULQ 56(SP) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 312(SP),AX - MULQ 64(SP) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ 312(SP),AX - MULQ 72(SP) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 312(SP),DX - IMUL3Q $19,DX,AX - MULQ 80(SP) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 312(SP),DX - IMUL3Q $19,DX,AX - MULQ 88(SP) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 320(SP),AX - MULQ 56(SP) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ 320(SP),AX - MULQ 64(SP) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 256(SP),AX - MULQ 80(SP) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 256(SP),AX - MULQ 88(SP) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 328(SP),AX - MULQ 56(SP) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 264(SP),AX - MULQ 72(SP) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 264(SP),AX - MULQ 80(SP) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 264(SP),AX - MULQ 88(SP) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ ·REDMASK51(SB),DX - SHLQ $13,CX:SI - ANDQ DX,SI - SHLQ $13,R9:R8 - ANDQ DX,R8 - ADDQ CX,R8 - SHLQ $13,R11:R10 - ANDQ DX,R10 - ADDQ R9,R10 - SHLQ $13,R13:R12 - ANDQ DX,R12 - ADDQ R11,R12 - SHLQ $13,R15:R14 - ANDQ DX,R14 - ADDQ R13,R14 - IMUL3Q $19,R15,CX - ADDQ CX,SI - MOVQ SI,CX - SHRQ $51,CX - ADDQ R8,CX - MOVQ CX,R8 - SHRQ $51,CX - ANDQ DX,SI - ADDQ R10,CX - MOVQ CX,R9 - SHRQ $51,CX - ANDQ DX,R8 - ADDQ R12,CX - MOVQ CX,AX - SHRQ $51,CX - ANDQ DX,R9 - ADDQ R14,CX - MOVQ CX,R10 - SHRQ $51,CX - ANDQ DX,AX - IMUL3Q $19,CX,CX - ADDQ CX,SI - ANDQ DX,R10 - MOVQ SI,DX - MOVQ R8,CX - MOVQ R9,R11 - MOVQ AX,R12 - MOVQ R10,R13 - ADDQ ·_2P0(SB),DX - ADDQ ·_2P1234(SB),CX - ADDQ ·_2P1234(SB),R11 - ADDQ ·_2P1234(SB),R12 - ADDQ ·_2P1234(SB),R13 - ADDQ 96(SP),SI - ADDQ 104(SP),R8 - ADDQ 112(SP),R9 - ADDQ 120(SP),AX - ADDQ 128(SP),R10 - SUBQ 96(SP),DX - SUBQ 104(SP),CX - SUBQ 112(SP),R11 - SUBQ 120(SP),R12 - SUBQ 128(SP),R13 - MOVQ SI,120(DI) - MOVQ R8,128(DI) - MOVQ R9,136(DI) - MOVQ AX,144(DI) - MOVQ R10,152(DI) - MOVQ DX,160(DI) - MOVQ CX,168(DI) - MOVQ R11,176(DI) - MOVQ R12,184(DI) - MOVQ R13,192(DI) - MOVQ 120(DI),AX - MULQ 120(DI) - MOVQ AX,SI - MOVQ DX,CX - MOVQ 120(DI),AX - SHLQ $1,AX - MULQ 128(DI) - MOVQ AX,R8 - MOVQ DX,R9 - MOVQ 120(DI),AX - SHLQ $1,AX - MULQ 136(DI) - MOVQ AX,R10 - MOVQ DX,R11 - MOVQ 120(DI),AX - SHLQ $1,AX - MULQ 144(DI) - MOVQ AX,R12 - MOVQ DX,R13 - MOVQ 120(DI),AX - SHLQ $1,AX - MULQ 152(DI) - MOVQ AX,R14 - MOVQ DX,R15 - MOVQ 128(DI),AX - MULQ 128(DI) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 128(DI),AX - SHLQ $1,AX - MULQ 136(DI) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ 128(DI),AX - SHLQ $1,AX - MULQ 144(DI) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 128(DI),DX - IMUL3Q $38,DX,AX - MULQ 152(DI) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 136(DI),AX - MULQ 136(DI) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 136(DI),DX - IMUL3Q $38,DX,AX - MULQ 144(DI) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 136(DI),DX - IMUL3Q $38,DX,AX - MULQ 152(DI) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 144(DI),DX - IMUL3Q $19,DX,AX - MULQ 144(DI) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 144(DI),DX - IMUL3Q $38,DX,AX - MULQ 152(DI) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 152(DI),DX - IMUL3Q $19,DX,AX - MULQ 152(DI) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ ·REDMASK51(SB),DX - SHLQ $13,CX:SI - ANDQ DX,SI - SHLQ $13,R9:R8 - ANDQ DX,R8 - ADDQ CX,R8 - SHLQ $13,R11:R10 - ANDQ DX,R10 - ADDQ R9,R10 - SHLQ $13,R13:R12 - ANDQ DX,R12 - ADDQ R11,R12 - SHLQ $13,R15:R14 - ANDQ DX,R14 - ADDQ R13,R14 - IMUL3Q $19,R15,CX - ADDQ CX,SI - MOVQ SI,CX - SHRQ $51,CX - ADDQ R8,CX - ANDQ DX,SI - MOVQ CX,R8 - SHRQ $51,CX - ADDQ R10,CX - ANDQ DX,R8 - MOVQ CX,R9 - SHRQ $51,CX - ADDQ R12,CX - ANDQ DX,R9 - MOVQ CX,AX - SHRQ $51,CX - ADDQ R14,CX - ANDQ DX,AX - MOVQ CX,R10 - SHRQ $51,CX - IMUL3Q $19,CX,CX - ADDQ CX,SI - ANDQ DX,R10 - MOVQ SI,120(DI) - MOVQ R8,128(DI) - MOVQ R9,136(DI) - MOVQ AX,144(DI) - MOVQ R10,152(DI) - MOVQ 160(DI),AX - MULQ 160(DI) - MOVQ AX,SI - MOVQ DX,CX - MOVQ 160(DI),AX - SHLQ $1,AX - MULQ 168(DI) - MOVQ AX,R8 - MOVQ DX,R9 - MOVQ 160(DI),AX - SHLQ $1,AX - MULQ 176(DI) - MOVQ AX,R10 - MOVQ DX,R11 - MOVQ 160(DI),AX - SHLQ $1,AX - MULQ 184(DI) - MOVQ AX,R12 - MOVQ DX,R13 - MOVQ 160(DI),AX - SHLQ $1,AX - MULQ 192(DI) - MOVQ AX,R14 - MOVQ DX,R15 - MOVQ 168(DI),AX - MULQ 168(DI) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 168(DI),AX - SHLQ $1,AX - MULQ 176(DI) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ 168(DI),AX - SHLQ $1,AX - MULQ 184(DI) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 168(DI),DX - IMUL3Q $38,DX,AX - MULQ 192(DI) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 176(DI),AX - MULQ 176(DI) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 176(DI),DX - IMUL3Q $38,DX,AX - MULQ 184(DI) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 176(DI),DX - IMUL3Q $38,DX,AX - MULQ 192(DI) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 184(DI),DX - IMUL3Q $19,DX,AX - MULQ 184(DI) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 184(DI),DX - IMUL3Q $38,DX,AX - MULQ 192(DI) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 192(DI),DX - IMUL3Q $19,DX,AX - MULQ 192(DI) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ ·REDMASK51(SB),DX - SHLQ $13,CX:SI - ANDQ DX,SI - SHLQ $13,R9:R8 - ANDQ DX,R8 - ADDQ CX,R8 - SHLQ $13,R11:R10 - ANDQ DX,R10 - ADDQ R9,R10 - SHLQ $13,R13:R12 - ANDQ DX,R12 - ADDQ R11,R12 - SHLQ $13,R15:R14 - ANDQ DX,R14 - ADDQ R13,R14 - IMUL3Q $19,R15,CX - ADDQ CX,SI - MOVQ SI,CX - SHRQ $51,CX - ADDQ R8,CX - ANDQ DX,SI - MOVQ CX,R8 - SHRQ $51,CX - ADDQ R10,CX - ANDQ DX,R8 - MOVQ CX,R9 - SHRQ $51,CX - ADDQ R12,CX - ANDQ DX,R9 - MOVQ CX,AX - SHRQ $51,CX - ADDQ R14,CX - ANDQ DX,AX - MOVQ CX,R10 - SHRQ $51,CX - IMUL3Q $19,CX,CX - ADDQ CX,SI - ANDQ DX,R10 - MOVQ SI,160(DI) - MOVQ R8,168(DI) - MOVQ R9,176(DI) - MOVQ AX,184(DI) - MOVQ R10,192(DI) - MOVQ 184(DI),SI - IMUL3Q $19,SI,AX - MOVQ AX,56(SP) - MULQ 16(DI) - MOVQ AX,SI - MOVQ DX,CX - MOVQ 192(DI),DX - IMUL3Q $19,DX,AX - MOVQ AX,64(SP) - MULQ 8(DI) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 160(DI),AX - MULQ 0(DI) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 160(DI),AX - MULQ 8(DI) - MOVQ AX,R8 - MOVQ DX,R9 - MOVQ 160(DI),AX - MULQ 16(DI) - MOVQ AX,R10 - MOVQ DX,R11 - MOVQ 160(DI),AX - MULQ 24(DI) - MOVQ AX,R12 - MOVQ DX,R13 - MOVQ 160(DI),AX - MULQ 32(DI) - MOVQ AX,R14 - MOVQ DX,R15 - MOVQ 168(DI),AX - MULQ 0(DI) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 168(DI),AX - MULQ 8(DI) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 168(DI),AX - MULQ 16(DI) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ 168(DI),AX - MULQ 24(DI) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 168(DI),DX - IMUL3Q $19,DX,AX - MULQ 32(DI) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 176(DI),AX - MULQ 0(DI) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 176(DI),AX - MULQ 8(DI) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ 176(DI),AX - MULQ 16(DI) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 176(DI),DX - IMUL3Q $19,DX,AX - MULQ 24(DI) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 176(DI),DX - IMUL3Q $19,DX,AX - MULQ 32(DI) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 184(DI),AX - MULQ 0(DI) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ 184(DI),AX - MULQ 8(DI) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 56(SP),AX - MULQ 24(DI) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 56(SP),AX - MULQ 32(DI) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 192(DI),AX - MULQ 0(DI) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 64(SP),AX - MULQ 16(DI) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 64(SP),AX - MULQ 24(DI) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 64(SP),AX - MULQ 32(DI) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ ·REDMASK51(SB),DX - SHLQ $13,CX:SI - ANDQ DX,SI - SHLQ $13,R9:R8 - ANDQ DX,R8 - ADDQ CX,R8 - SHLQ $13,R11:R10 - ANDQ DX,R10 - ADDQ R9,R10 - SHLQ $13,R13:R12 - ANDQ DX,R12 - ADDQ R11,R12 - SHLQ $13,R15:R14 - ANDQ DX,R14 - ADDQ R13,R14 - IMUL3Q $19,R15,CX - ADDQ CX,SI - MOVQ SI,CX - SHRQ $51,CX - ADDQ R8,CX - MOVQ CX,R8 - SHRQ $51,CX - ANDQ DX,SI - ADDQ R10,CX - MOVQ CX,R9 - SHRQ $51,CX - ANDQ DX,R8 - ADDQ R12,CX - MOVQ CX,AX - SHRQ $51,CX - ANDQ DX,R9 - ADDQ R14,CX - MOVQ CX,R10 - SHRQ $51,CX - ANDQ DX,AX - IMUL3Q $19,CX,CX - ADDQ CX,SI - ANDQ DX,R10 - MOVQ SI,160(DI) - MOVQ R8,168(DI) - MOVQ R9,176(DI) - MOVQ AX,184(DI) - MOVQ R10,192(DI) - MOVQ 200(SP),SI - IMUL3Q $19,SI,AX - MOVQ AX,56(SP) - MULQ 152(SP) - MOVQ AX,SI - MOVQ DX,CX - MOVQ 208(SP),DX - IMUL3Q $19,DX,AX - MOVQ AX,64(SP) - MULQ 144(SP) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 176(SP),AX - MULQ 136(SP) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 176(SP),AX - MULQ 144(SP) - MOVQ AX,R8 - MOVQ DX,R9 - MOVQ 176(SP),AX - MULQ 152(SP) - MOVQ AX,R10 - MOVQ DX,R11 - MOVQ 176(SP),AX - MULQ 160(SP) - MOVQ AX,R12 - MOVQ DX,R13 - MOVQ 176(SP),AX - MULQ 168(SP) - MOVQ AX,R14 - MOVQ DX,R15 - MOVQ 184(SP),AX - MULQ 136(SP) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 184(SP),AX - MULQ 144(SP) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 184(SP),AX - MULQ 152(SP) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ 184(SP),AX - MULQ 160(SP) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 184(SP),DX - IMUL3Q $19,DX,AX - MULQ 168(SP) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 192(SP),AX - MULQ 136(SP) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 192(SP),AX - MULQ 144(SP) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ 192(SP),AX - MULQ 152(SP) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 192(SP),DX - IMUL3Q $19,DX,AX - MULQ 160(SP) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 192(SP),DX - IMUL3Q $19,DX,AX - MULQ 168(SP) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 200(SP),AX - MULQ 136(SP) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ 200(SP),AX - MULQ 144(SP) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 56(SP),AX - MULQ 160(SP) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 56(SP),AX - MULQ 168(SP) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 208(SP),AX - MULQ 136(SP) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 64(SP),AX - MULQ 152(SP) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 64(SP),AX - MULQ 160(SP) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 64(SP),AX - MULQ 168(SP) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ ·REDMASK51(SB),DX - SHLQ $13,CX:SI - ANDQ DX,SI - SHLQ $13,R9:R8 - ANDQ DX,R8 - ADDQ CX,R8 - SHLQ $13,R11:R10 - ANDQ DX,R10 - ADDQ R9,R10 - SHLQ $13,R13:R12 - ANDQ DX,R12 - ADDQ R11,R12 - SHLQ $13,R15:R14 - ANDQ DX,R14 - ADDQ R13,R14 - IMUL3Q $19,R15,CX - ADDQ CX,SI - MOVQ SI,CX - SHRQ $51,CX - ADDQ R8,CX - MOVQ CX,R8 - SHRQ $51,CX - ANDQ DX,SI - ADDQ R10,CX - MOVQ CX,R9 - SHRQ $51,CX - ANDQ DX,R8 - ADDQ R12,CX - MOVQ CX,AX - SHRQ $51,CX - ANDQ DX,R9 - ADDQ R14,CX - MOVQ CX,R10 - SHRQ $51,CX - ANDQ DX,AX - IMUL3Q $19,CX,CX - ADDQ CX,SI - ANDQ DX,R10 - MOVQ SI,40(DI) - MOVQ R8,48(DI) - MOVQ R9,56(DI) - MOVQ AX,64(DI) - MOVQ R10,72(DI) - MOVQ 216(SP),AX - MULQ ·_121666_213(SB) - SHRQ $13,AX - MOVQ AX,SI - MOVQ DX,CX - MOVQ 224(SP),AX - MULQ ·_121666_213(SB) - SHRQ $13,AX - ADDQ AX,CX - MOVQ DX,R8 - MOVQ 232(SP),AX - MULQ ·_121666_213(SB) - SHRQ $13,AX - ADDQ AX,R8 - MOVQ DX,R9 - MOVQ 240(SP),AX - MULQ ·_121666_213(SB) - SHRQ $13,AX - ADDQ AX,R9 - MOVQ DX,R10 - MOVQ 248(SP),AX - MULQ ·_121666_213(SB) - SHRQ $13,AX - ADDQ AX,R10 - IMUL3Q $19,DX,DX - ADDQ DX,SI - ADDQ 136(SP),SI - ADDQ 144(SP),CX - ADDQ 152(SP),R8 - ADDQ 160(SP),R9 - ADDQ 168(SP),R10 - MOVQ SI,80(DI) - MOVQ CX,88(DI) - MOVQ R8,96(DI) - MOVQ R9,104(DI) - MOVQ R10,112(DI) - MOVQ 104(DI),SI - IMUL3Q $19,SI,AX - MOVQ AX,56(SP) - MULQ 232(SP) - MOVQ AX,SI - MOVQ DX,CX - MOVQ 112(DI),DX - IMUL3Q $19,DX,AX - MOVQ AX,64(SP) - MULQ 224(SP) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 80(DI),AX - MULQ 216(SP) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 80(DI),AX - MULQ 224(SP) - MOVQ AX,R8 - MOVQ DX,R9 - MOVQ 80(DI),AX - MULQ 232(SP) - MOVQ AX,R10 - MOVQ DX,R11 - MOVQ 80(DI),AX - MULQ 240(SP) - MOVQ AX,R12 - MOVQ DX,R13 - MOVQ 80(DI),AX - MULQ 248(SP) - MOVQ AX,R14 - MOVQ DX,R15 - MOVQ 88(DI),AX - MULQ 216(SP) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 88(DI),AX - MULQ 224(SP) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 88(DI),AX - MULQ 232(SP) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ 88(DI),AX - MULQ 240(SP) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 88(DI),DX - IMUL3Q $19,DX,AX - MULQ 248(SP) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 96(DI),AX - MULQ 216(SP) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 96(DI),AX - MULQ 224(SP) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ 96(DI),AX - MULQ 232(SP) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 96(DI),DX - IMUL3Q $19,DX,AX - MULQ 240(SP) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 96(DI),DX - IMUL3Q $19,DX,AX - MULQ 248(SP) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 104(DI),AX - MULQ 216(SP) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ 104(DI),AX - MULQ 224(SP) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 56(SP),AX - MULQ 240(SP) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 56(SP),AX - MULQ 248(SP) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 112(DI),AX - MULQ 216(SP) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 64(SP),AX - MULQ 232(SP) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 64(SP),AX - MULQ 240(SP) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 64(SP),AX - MULQ 248(SP) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ ·REDMASK51(SB),DX - SHLQ $13,CX:SI - ANDQ DX,SI - SHLQ $13,R9:R8 - ANDQ DX,R8 - ADDQ CX,R8 - SHLQ $13,R11:R10 - ANDQ DX,R10 - ADDQ R9,R10 - SHLQ $13,R13:R12 - ANDQ DX,R12 - ADDQ R11,R12 - SHLQ $13,R15:R14 - ANDQ DX,R14 - ADDQ R13,R14 - IMUL3Q $19,R15,CX - ADDQ CX,SI - MOVQ SI,CX - SHRQ $51,CX - ADDQ R8,CX - MOVQ CX,R8 - SHRQ $51,CX - ANDQ DX,SI - ADDQ R10,CX - MOVQ CX,R9 - SHRQ $51,CX - ANDQ DX,R8 - ADDQ R12,CX - MOVQ CX,AX - SHRQ $51,CX - ANDQ DX,R9 - ADDQ R14,CX - MOVQ CX,R10 - SHRQ $51,CX - ANDQ DX,AX - IMUL3Q $19,CX,CX - ADDQ CX,SI - ANDQ DX,R10 - MOVQ SI,80(DI) - MOVQ R8,88(DI) - MOVQ R9,96(DI) - MOVQ AX,104(DI) - MOVQ R10,112(DI) - MOVQ 0(SP),R11 - MOVQ 8(SP),R12 - MOVQ 16(SP),R13 - MOVQ 24(SP),R14 - MOVQ 32(SP),R15 - MOVQ 40(SP),BX - MOVQ 48(SP),BP - MOVQ R11,SP - MOVQ DI,AX - MOVQ SI,DX - RET diff --git a/vendor/golang.org/x/crypto/curve25519/mont25519_amd64.go b/vendor/golang.org/x/crypto/curve25519/mont25519_amd64.go deleted file mode 100644 index 5822bd5..0000000 --- a/vendor/golang.org/x/crypto/curve25519/mont25519_amd64.go +++ /dev/null @@ -1,240 +0,0 @@ -// Copyright 2012 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 amd64,!gccgo,!appengine - -package curve25519 - -// These functions are implemented in the .s files. The names of the functions -// in the rest of the file are also taken from the SUPERCOP sources to help -// people following along. - -//go:noescape - -func cswap(inout *[5]uint64, v uint64) - -//go:noescape - -func ladderstep(inout *[5][5]uint64) - -//go:noescape - -func freeze(inout *[5]uint64) - -//go:noescape - -func mul(dest, a, b *[5]uint64) - -//go:noescape - -func square(out, in *[5]uint64) - -// mladder uses a Montgomery ladder to calculate (xr/zr) *= s. -func mladder(xr, zr *[5]uint64, s *[32]byte) { - var work [5][5]uint64 - - work[0] = *xr - setint(&work[1], 1) - setint(&work[2], 0) - work[3] = *xr - setint(&work[4], 1) - - j := uint(6) - var prevbit byte - - for i := 31; i >= 0; i-- { - for j < 8 { - bit := ((*s)[i] >> j) & 1 - swap := bit ^ prevbit - prevbit = bit - cswap(&work[1], uint64(swap)) - ladderstep(&work) - j-- - } - j = 7 - } - - *xr = work[1] - *zr = work[2] -} - -func scalarMult(out, in, base *[32]byte) { - var e [32]byte - copy(e[:], (*in)[:]) - e[0] &= 248 - e[31] &= 127 - e[31] |= 64 - - var t, z [5]uint64 - unpack(&t, base) - mladder(&t, &z, &e) - invert(&z, &z) - mul(&t, &t, &z) - pack(out, &t) -} - -func setint(r *[5]uint64, v uint64) { - r[0] = v - r[1] = 0 - r[2] = 0 - r[3] = 0 - r[4] = 0 -} - -// unpack sets r = x where r consists of 5, 51-bit limbs in little-endian -// order. -func unpack(r *[5]uint64, x *[32]byte) { - r[0] = uint64(x[0]) | - uint64(x[1])<<8 | - uint64(x[2])<<16 | - uint64(x[3])<<24 | - uint64(x[4])<<32 | - uint64(x[5])<<40 | - uint64(x[6]&7)<<48 - - r[1] = uint64(x[6])>>3 | - uint64(x[7])<<5 | - uint64(x[8])<<13 | - uint64(x[9])<<21 | - uint64(x[10])<<29 | - uint64(x[11])<<37 | - uint64(x[12]&63)<<45 - - r[2] = uint64(x[12])>>6 | - uint64(x[13])<<2 | - uint64(x[14])<<10 | - uint64(x[15])<<18 | - uint64(x[16])<<26 | - uint64(x[17])<<34 | - uint64(x[18])<<42 | - uint64(x[19]&1)<<50 - - r[3] = uint64(x[19])>>1 | - uint64(x[20])<<7 | - uint64(x[21])<<15 | - uint64(x[22])<<23 | - uint64(x[23])<<31 | - uint64(x[24])<<39 | - uint64(x[25]&15)<<47 - - r[4] = uint64(x[25])>>4 | - uint64(x[26])<<4 | - uint64(x[27])<<12 | - uint64(x[28])<<20 | - uint64(x[29])<<28 | - uint64(x[30])<<36 | - uint64(x[31]&127)<<44 -} - -// pack sets out = x where out is the usual, little-endian form of the 5, -// 51-bit limbs in x. -func pack(out *[32]byte, x *[5]uint64) { - t := *x - freeze(&t) - - out[0] = byte(t[0]) - out[1] = byte(t[0] >> 8) - out[2] = byte(t[0] >> 16) - out[3] = byte(t[0] >> 24) - out[4] = byte(t[0] >> 32) - out[5] = byte(t[0] >> 40) - out[6] = byte(t[0] >> 48) - - out[6] ^= byte(t[1]<<3) & 0xf8 - out[7] = byte(t[1] >> 5) - out[8] = byte(t[1] >> 13) - out[9] = byte(t[1] >> 21) - out[10] = byte(t[1] >> 29) - out[11] = byte(t[1] >> 37) - out[12] = byte(t[1] >> 45) - - out[12] ^= byte(t[2]<<6) & 0xc0 - out[13] = byte(t[2] >> 2) - out[14] = byte(t[2] >> 10) - out[15] = byte(t[2] >> 18) - out[16] = byte(t[2] >> 26) - out[17] = byte(t[2] >> 34) - out[18] = byte(t[2] >> 42) - out[19] = byte(t[2] >> 50) - - out[19] ^= byte(t[3]<<1) & 0xfe - out[20] = byte(t[3] >> 7) - out[21] = byte(t[3] >> 15) - out[22] = byte(t[3] >> 23) - out[23] = byte(t[3] >> 31) - out[24] = byte(t[3] >> 39) - out[25] = byte(t[3] >> 47) - - out[25] ^= byte(t[4]<<4) & 0xf0 - out[26] = byte(t[4] >> 4) - out[27] = byte(t[4] >> 12) - out[28] = byte(t[4] >> 20) - out[29] = byte(t[4] >> 28) - out[30] = byte(t[4] >> 36) - out[31] = byte(t[4] >> 44) -} - -// invert calculates r = x^-1 mod p using Fermat's little theorem. -func invert(r *[5]uint64, x *[5]uint64) { - var z2, z9, z11, z2_5_0, z2_10_0, z2_20_0, z2_50_0, z2_100_0, t [5]uint64 - - square(&z2, x) /* 2 */ - square(&t, &z2) /* 4 */ - square(&t, &t) /* 8 */ - mul(&z9, &t, x) /* 9 */ - mul(&z11, &z9, &z2) /* 11 */ - square(&t, &z11) /* 22 */ - mul(&z2_5_0, &t, &z9) /* 2^5 - 2^0 = 31 */ - - square(&t, &z2_5_0) /* 2^6 - 2^1 */ - for i := 1; i < 5; i++ { /* 2^20 - 2^10 */ - square(&t, &t) - } - mul(&z2_10_0, &t, &z2_5_0) /* 2^10 - 2^0 */ - - square(&t, &z2_10_0) /* 2^11 - 2^1 */ - for i := 1; i < 10; i++ { /* 2^20 - 2^10 */ - square(&t, &t) - } - mul(&z2_20_0, &t, &z2_10_0) /* 2^20 - 2^0 */ - - square(&t, &z2_20_0) /* 2^21 - 2^1 */ - for i := 1; i < 20; i++ { /* 2^40 - 2^20 */ - square(&t, &t) - } - mul(&t, &t, &z2_20_0) /* 2^40 - 2^0 */ - - square(&t, &t) /* 2^41 - 2^1 */ - for i := 1; i < 10; i++ { /* 2^50 - 2^10 */ - square(&t, &t) - } - mul(&z2_50_0, &t, &z2_10_0) /* 2^50 - 2^0 */ - - square(&t, &z2_50_0) /* 2^51 - 2^1 */ - for i := 1; i < 50; i++ { /* 2^100 - 2^50 */ - square(&t, &t) - } - mul(&z2_100_0, &t, &z2_50_0) /* 2^100 - 2^0 */ - - square(&t, &z2_100_0) /* 2^101 - 2^1 */ - for i := 1; i < 100; i++ { /* 2^200 - 2^100 */ - square(&t, &t) - } - mul(&t, &t, &z2_100_0) /* 2^200 - 2^0 */ - - square(&t, &t) /* 2^201 - 2^1 */ - for i := 1; i < 50; i++ { /* 2^250 - 2^50 */ - square(&t, &t) - } - mul(&t, &t, &z2_50_0) /* 2^250 - 2^0 */ - - square(&t, &t) /* 2^251 - 2^1 */ - square(&t, &t) /* 2^252 - 2^2 */ - square(&t, &t) /* 2^253 - 2^3 */ - - square(&t, &t) /* 2^254 - 2^4 */ - - square(&t, &t) /* 2^255 - 2^5 */ - mul(r, &t, &z11) /* 2^255 - 21 */ -} diff --git a/vendor/golang.org/x/crypto/curve25519/mul_amd64.s b/vendor/golang.org/x/crypto/curve25519/mul_amd64.s deleted file mode 100644 index e48d183..0000000 --- a/vendor/golang.org/x/crypto/curve25519/mul_amd64.s +++ /dev/null @@ -1,191 +0,0 @@ -// Copyright 2012 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. - -// This code was translated into a form compatible with 6a from the public -// domain sources in SUPERCOP: http://bench.cr.yp.to/supercop.html - -// +build amd64,!gccgo,!appengine - -// func mul(dest, a, b *[5]uint64) -TEXT ·mul(SB),0,$128-24 - MOVQ dest+0(FP), DI - MOVQ a+8(FP), SI - MOVQ b+16(FP), DX - - MOVQ SP,R11 - MOVQ $31,CX - NOTQ CX - ANDQ CX,SP - ADDQ $32,SP - - MOVQ R11,0(SP) - MOVQ R12,8(SP) - MOVQ R13,16(SP) - MOVQ R14,24(SP) - MOVQ R15,32(SP) - MOVQ BX,40(SP) - MOVQ BP,48(SP) - MOVQ DI,56(SP) - MOVQ DX,CX - MOVQ 24(SI),DX - IMUL3Q $19,DX,AX - MOVQ AX,64(SP) - MULQ 16(CX) - MOVQ AX,R8 - MOVQ DX,R9 - MOVQ 32(SI),DX - IMUL3Q $19,DX,AX - MOVQ AX,72(SP) - MULQ 8(CX) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 0(SI),AX - MULQ 0(CX) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 0(SI),AX - MULQ 8(CX) - MOVQ AX,R10 - MOVQ DX,R11 - MOVQ 0(SI),AX - MULQ 16(CX) - MOVQ AX,R12 - MOVQ DX,R13 - MOVQ 0(SI),AX - MULQ 24(CX) - MOVQ AX,R14 - MOVQ DX,R15 - MOVQ 0(SI),AX - MULQ 32(CX) - MOVQ AX,BX - MOVQ DX,BP - MOVQ 8(SI),AX - MULQ 0(CX) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 8(SI),AX - MULQ 8(CX) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ 8(SI),AX - MULQ 16(CX) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 8(SI),AX - MULQ 24(CX) - ADDQ AX,BX - ADCQ DX,BP - MOVQ 8(SI),DX - IMUL3Q $19,DX,AX - MULQ 32(CX) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 16(SI),AX - MULQ 0(CX) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ 16(SI),AX - MULQ 8(CX) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 16(SI),AX - MULQ 16(CX) - ADDQ AX,BX - ADCQ DX,BP - MOVQ 16(SI),DX - IMUL3Q $19,DX,AX - MULQ 24(CX) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 16(SI),DX - IMUL3Q $19,DX,AX - MULQ 32(CX) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 24(SI),AX - MULQ 0(CX) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 24(SI),AX - MULQ 8(CX) - ADDQ AX,BX - ADCQ DX,BP - MOVQ 64(SP),AX - MULQ 24(CX) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 64(SP),AX - MULQ 32(CX) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ 32(SI),AX - MULQ 0(CX) - ADDQ AX,BX - ADCQ DX,BP - MOVQ 72(SP),AX - MULQ 16(CX) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 72(SP),AX - MULQ 24(CX) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ 72(SP),AX - MULQ 32(CX) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ ·REDMASK51(SB),SI - SHLQ $13,R9:R8 - ANDQ SI,R8 - SHLQ $13,R11:R10 - ANDQ SI,R10 - ADDQ R9,R10 - SHLQ $13,R13:R12 - ANDQ SI,R12 - ADDQ R11,R12 - SHLQ $13,R15:R14 - ANDQ SI,R14 - ADDQ R13,R14 - SHLQ $13,BP:BX - ANDQ SI,BX - ADDQ R15,BX - IMUL3Q $19,BP,DX - ADDQ DX,R8 - MOVQ R8,DX - SHRQ $51,DX - ADDQ R10,DX - MOVQ DX,CX - SHRQ $51,DX - ANDQ SI,R8 - ADDQ R12,DX - MOVQ DX,R9 - SHRQ $51,DX - ANDQ SI,CX - ADDQ R14,DX - MOVQ DX,AX - SHRQ $51,DX - ANDQ SI,R9 - ADDQ BX,DX - MOVQ DX,R10 - SHRQ $51,DX - ANDQ SI,AX - IMUL3Q $19,DX,DX - ADDQ DX,R8 - ANDQ SI,R10 - MOVQ R8,0(DI) - MOVQ CX,8(DI) - MOVQ R9,16(DI) - MOVQ AX,24(DI) - MOVQ R10,32(DI) - MOVQ 0(SP),R11 - MOVQ 8(SP),R12 - MOVQ 16(SP),R13 - MOVQ 24(SP),R14 - MOVQ 32(SP),R15 - MOVQ 40(SP),BX - MOVQ 48(SP),BP - MOVQ R11,SP - MOVQ DI,AX - MOVQ SI,DX - RET diff --git a/vendor/golang.org/x/crypto/curve25519/square_amd64.s b/vendor/golang.org/x/crypto/curve25519/square_amd64.s deleted file mode 100644 index 78d1a50..0000000 --- a/vendor/golang.org/x/crypto/curve25519/square_amd64.s +++ /dev/null @@ -1,153 +0,0 @@ -// Copyright 2012 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. - -// This code was translated into a form compatible with 6a from the public -// domain sources in SUPERCOP: http://bench.cr.yp.to/supercop.html - -// +build amd64,!gccgo,!appengine - -// func square(out, in *[5]uint64) -TEXT ·square(SB),7,$96-16 - MOVQ out+0(FP), DI - MOVQ in+8(FP), SI - - MOVQ SP,R11 - MOVQ $31,CX - NOTQ CX - ANDQ CX,SP - ADDQ $32, SP - - MOVQ R11,0(SP) - MOVQ R12,8(SP) - MOVQ R13,16(SP) - MOVQ R14,24(SP) - MOVQ R15,32(SP) - MOVQ BX,40(SP) - MOVQ BP,48(SP) - MOVQ 0(SI),AX - MULQ 0(SI) - MOVQ AX,CX - MOVQ DX,R8 - MOVQ 0(SI),AX - SHLQ $1,AX - MULQ 8(SI) - MOVQ AX,R9 - MOVQ DX,R10 - MOVQ 0(SI),AX - SHLQ $1,AX - MULQ 16(SI) - MOVQ AX,R11 - MOVQ DX,R12 - MOVQ 0(SI),AX - SHLQ $1,AX - MULQ 24(SI) - MOVQ AX,R13 - MOVQ DX,R14 - MOVQ 0(SI),AX - SHLQ $1,AX - MULQ 32(SI) - MOVQ AX,R15 - MOVQ DX,BX - MOVQ 8(SI),AX - MULQ 8(SI) - ADDQ AX,R11 - ADCQ DX,R12 - MOVQ 8(SI),AX - SHLQ $1,AX - MULQ 16(SI) - ADDQ AX,R13 - ADCQ DX,R14 - MOVQ 8(SI),AX - SHLQ $1,AX - MULQ 24(SI) - ADDQ AX,R15 - ADCQ DX,BX - MOVQ 8(SI),DX - IMUL3Q $38,DX,AX - MULQ 32(SI) - ADDQ AX,CX - ADCQ DX,R8 - MOVQ 16(SI),AX - MULQ 16(SI) - ADDQ AX,R15 - ADCQ DX,BX - MOVQ 16(SI),DX - IMUL3Q $38,DX,AX - MULQ 24(SI) - ADDQ AX,CX - ADCQ DX,R8 - MOVQ 16(SI),DX - IMUL3Q $38,DX,AX - MULQ 32(SI) - ADDQ AX,R9 - ADCQ DX,R10 - MOVQ 24(SI),DX - IMUL3Q $19,DX,AX - MULQ 24(SI) - ADDQ AX,R9 - ADCQ DX,R10 - MOVQ 24(SI),DX - IMUL3Q $38,DX,AX - MULQ 32(SI) - ADDQ AX,R11 - ADCQ DX,R12 - MOVQ 32(SI),DX - IMUL3Q $19,DX,AX - MULQ 32(SI) - ADDQ AX,R13 - ADCQ DX,R14 - MOVQ ·REDMASK51(SB),SI - SHLQ $13,R8:CX - ANDQ SI,CX - SHLQ $13,R10:R9 - ANDQ SI,R9 - ADDQ R8,R9 - SHLQ $13,R12:R11 - ANDQ SI,R11 - ADDQ R10,R11 - SHLQ $13,R14:R13 - ANDQ SI,R13 - ADDQ R12,R13 - SHLQ $13,BX:R15 - ANDQ SI,R15 - ADDQ R14,R15 - IMUL3Q $19,BX,DX - ADDQ DX,CX - MOVQ CX,DX - SHRQ $51,DX - ADDQ R9,DX - ANDQ SI,CX - MOVQ DX,R8 - SHRQ $51,DX - ADDQ R11,DX - ANDQ SI,R8 - MOVQ DX,R9 - SHRQ $51,DX - ADDQ R13,DX - ANDQ SI,R9 - MOVQ DX,AX - SHRQ $51,DX - ADDQ R15,DX - ANDQ SI,AX - MOVQ DX,R10 - SHRQ $51,DX - IMUL3Q $19,DX,DX - ADDQ DX,CX - ANDQ SI,R10 - MOVQ CX,0(DI) - MOVQ R8,8(DI) - MOVQ R9,16(DI) - MOVQ AX,24(DI) - MOVQ R10,32(DI) - MOVQ 0(SP),R11 - MOVQ 8(SP),R12 - MOVQ 16(SP),R13 - MOVQ 24(SP),R14 - MOVQ 32(SP),R15 - MOVQ 40(SP),BX - MOVQ 48(SP),BP - MOVQ R11,SP - MOVQ DI,AX - MOVQ SI,DX - RET diff --git a/vendor/golang.org/x/crypto/ed25519/ed25519.go b/vendor/golang.org/x/crypto/ed25519/ed25519.go deleted file mode 100644 index f1d9567..0000000 --- a/vendor/golang.org/x/crypto/ed25519/ed25519.go +++ /dev/null @@ -1,181 +0,0 @@ -// Copyright 2016 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 ed25519 implements the Ed25519 signature algorithm. See -// http://ed25519.cr.yp.to/. -// -// These functions are also compatible with the “Ed25519” function defined in -// https://tools.ietf.org/html/draft-irtf-cfrg-eddsa-05. -package ed25519 - -// This code is a port of the public domain, “ref10” implementation of ed25519 -// from SUPERCOP. - -import ( - "crypto" - cryptorand "crypto/rand" - "crypto/sha512" - "crypto/subtle" - "errors" - "io" - "strconv" - - "golang.org/x/crypto/ed25519/internal/edwards25519" -) - -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 -) - -// PublicKey is the type of Ed25519 public keys. -type PublicKey []byte - -// PrivateKey is the type of Ed25519 private keys. It implements crypto.Signer. -type PrivateKey []byte - -// Public returns the PublicKey corresponding to priv. -func (priv PrivateKey) Public() crypto.PublicKey { - publicKey := make([]byte, PublicKeySize) - copy(publicKey, priv[32:]) - return PublicKey(publicKey) -} - -// Sign signs the given message with priv. -// Ed25519 performs two passes over messages to be signed and therefore cannot -// handle pre-hashed messages. Thus opts.HashFunc() must return zero to -// indicate the message hasn't been hashed. This can be achieved by passing -// crypto.Hash(0) as the value for opts. -func (priv PrivateKey) Sign(rand io.Reader, message []byte, opts crypto.SignerOpts) (signature []byte, err error) { - if opts.HashFunc() != crypto.Hash(0) { - return nil, errors.New("ed25519: cannot sign hashed message") - } - - return Sign(priv, message), nil -} - -// 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 PublicKey, privateKey PrivateKey, err error) { - if rand == nil { - rand = cryptorand.Reader - } - - privateKey = make([]byte, PrivateKeySize) - publicKey = make([]byte, PublicKeySize) - _, err = io.ReadFull(rand, privateKey[:32]) - if err != nil { - return nil, nil, err - } - - digest := sha512.Sum512(privateKey[:32]) - digest[0] &= 248 - digest[31] &= 127 - digest[31] |= 64 - - var A edwards25519.ExtendedGroupElement - var hBytes [32]byte - copy(hBytes[:], digest[:]) - edwards25519.GeScalarMultBase(&A, &hBytes) - var publicKeyBytes [32]byte - A.ToBytes(&publicKeyBytes) - - copy(privateKey[32:], publicKeyBytes[:]) - copy(publicKey, publicKeyBytes[:]) - - return publicKey, privateKey, nil -} - -// 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 { - if l := len(privateKey); l != PrivateKeySize { - panic("ed25519: bad private key length: " + strconv.Itoa(l)) - } - - h := sha512.New() - h.Write(privateKey[:32]) - - var digest1, messageDigest, hramDigest [64]byte - var expandedSecretKey [32]byte - h.Sum(digest1[:0]) - copy(expandedSecretKey[:], digest1[:]) - expandedSecretKey[0] &= 248 - expandedSecretKey[31] &= 63 - expandedSecretKey[31] |= 64 - - h.Reset() - h.Write(digest1[32:]) - h.Write(message) - h.Sum(messageDigest[:0]) - - var messageDigestReduced [32]byte - edwards25519.ScReduce(&messageDigestReduced, &messageDigest) - var R edwards25519.ExtendedGroupElement - edwards25519.GeScalarMultBase(&R, &messageDigestReduced) - - var encodedR [32]byte - R.ToBytes(&encodedR) - - h.Reset() - h.Write(encodedR[:]) - h.Write(privateKey[32:]) - h.Write(message) - h.Sum(hramDigest[:0]) - var hramDigestReduced [32]byte - edwards25519.ScReduce(&hramDigestReduced, &hramDigest) - - var s [32]byte - edwards25519.ScMulAdd(&s, &hramDigestReduced, &expandedSecretKey, &messageDigestReduced) - - signature := make([]byte, SignatureSize) - copy(signature[:], encodedR[:]) - copy(signature[32:], s[:]) - - return signature -} - -// 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 { - if l := len(publicKey); l != PublicKeySize { - panic("ed25519: bad public key length: " + strconv.Itoa(l)) - } - - if len(sig) != SignatureSize || sig[63]&224 != 0 { - return false - } - - var A edwards25519.ExtendedGroupElement - var publicKeyBytes [32]byte - copy(publicKeyBytes[:], publicKey) - if !A.FromBytes(&publicKeyBytes) { - return false - } - edwards25519.FeNeg(&A.X, &A.X) - edwards25519.FeNeg(&A.T, &A.T) - - h := sha512.New() - h.Write(sig[:32]) - h.Write(publicKey[:]) - h.Write(message) - var digest [64]byte - h.Sum(digest[:0]) - - var hReduced [32]byte - edwards25519.ScReduce(&hReduced, &digest) - - var R edwards25519.ProjectiveGroupElement - var b [32]byte - copy(b[:], sig[32:]) - edwards25519.GeDoubleScalarMultVartime(&R, &hReduced, &A, &b) - - var checkR [32]byte - R.ToBytes(&checkR) - return subtle.ConstantTimeCompare(sig[:32], checkR[:]) == 1 -} diff --git a/vendor/golang.org/x/crypto/ed25519/internal/edwards25519/const.go b/vendor/golang.org/x/crypto/ed25519/internal/edwards25519/const.go deleted file mode 100644 index e39f086..0000000 --- a/vendor/golang.org/x/crypto/ed25519/internal/edwards25519/const.go +++ /dev/null @@ -1,1422 +0,0 @@ -// Copyright 2016 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 edwards25519 - -// These values are from the public domain, “ref10” implementation of ed25519 -// from SUPERCOP. - -// d is a constant in the Edwards curve equation. -var d = FieldElement{ - -10913610, 13857413, -15372611, 6949391, 114729, -8787816, -6275908, -3247719, -18696448, -12055116, -} - -// d2 is 2*d. -var d2 = FieldElement{ - -21827239, -5839606, -30745221, 13898782, 229458, 15978800, -12551817, -6495438, 29715968, 9444199, -} - -// SqrtM1 is the square-root of -1 in the field. -var SqrtM1 = FieldElement{ - -32595792, -7943725, 9377950, 3500415, 12389472, -272473, -25146209, -2005654, 326686, 11406482, -} - -// A is a constant in the Montgomery-form of curve25519. -var A = FieldElement{ - 486662, 0, 0, 0, 0, 0, 0, 0, 0, 0, -} - -// bi contains precomputed multiples of the base-point. See the Ed25519 paper -// for a discussion about how these values are used. -var bi = [8]PreComputedGroupElement{ - { - FieldElement{25967493, -14356035, 29566456, 3660896, -12694345, 4014787, 27544626, -11754271, -6079156, 2047605}, - FieldElement{-12545711, 934262, -2722910, 3049990, -727428, 9406986, 12720692, 5043384, 19500929, -15469378}, - FieldElement{-8738181, 4489570, 9688441, -14785194, 10184609, -12363380, 29287919, 11864899, -24514362, -4438546}, - }, - { - FieldElement{15636291, -9688557, 24204773, -7912398, 616977, -16685262, 27787600, -14772189, 28944400, -1550024}, - FieldElement{16568933, 4717097, -11556148, -1102322, 15682896, -11807043, 16354577, -11775962, 7689662, 11199574}, - FieldElement{30464156, -5976125, -11779434, -15670865, 23220365, 15915852, 7512774, 10017326, -17749093, -9920357}, - }, - { - FieldElement{10861363, 11473154, 27284546, 1981175, -30064349, 12577861, 32867885, 14515107, -15438304, 10819380}, - FieldElement{4708026, 6336745, 20377586, 9066809, -11272109, 6594696, -25653668, 12483688, -12668491, 5581306}, - FieldElement{19563160, 16186464, -29386857, 4097519, 10237984, -4348115, 28542350, 13850243, -23678021, -15815942}, - }, - { - FieldElement{5153746, 9909285, 1723747, -2777874, 30523605, 5516873, 19480852, 5230134, -23952439, -15175766}, - FieldElement{-30269007, -3463509, 7665486, 10083793, 28475525, 1649722, 20654025, 16520125, 30598449, 7715701}, - FieldElement{28881845, 14381568, 9657904, 3680757, -20181635, 7843316, -31400660, 1370708, 29794553, -1409300}, - }, - { - FieldElement{-22518993, -6692182, 14201702, -8745502, -23510406, 8844726, 18474211, -1361450, -13062696, 13821877}, - FieldElement{-6455177, -7839871, 3374702, -4740862, -27098617, -10571707, 31655028, -7212327, 18853322, -14220951}, - FieldElement{4566830, -12963868, -28974889, -12240689, -7602672, -2830569, -8514358, -10431137, 2207753, -3209784}, - }, - { - FieldElement{-25154831, -4185821, 29681144, 7868801, -6854661, -9423865, -12437364, -663000, -31111463, -16132436}, - FieldElement{25576264, -2703214, 7349804, -11814844, 16472782, 9300885, 3844789, 15725684, 171356, 6466918}, - FieldElement{23103977, 13316479, 9739013, -16149481, 817875, -15038942, 8965339, -14088058, -30714912, 16193877}, - }, - { - FieldElement{-33521811, 3180713, -2394130, 14003687, -16903474, -16270840, 17238398, 4729455, -18074513, 9256800}, - FieldElement{-25182317, -4174131, 32336398, 5036987, -21236817, 11360617, 22616405, 9761698, -19827198, 630305}, - FieldElement{-13720693, 2639453, -24237460, -7406481, 9494427, -5774029, -6554551, -15960994, -2449256, -14291300}, - }, - { - FieldElement{-3151181, -5046075, 9282714, 6866145, -31907062, -863023, -18940575, 15033784, 25105118, -7894876}, - FieldElement{-24326370, 15950226, -31801215, -14592823, -11662737, -5090925, 1573892, -2625887, 2198790, -15804619}, - FieldElement{-3099351, 10324967, -2241613, 7453183, -5446979, -2735503, -13812022, -16236442, -32461234, -12290683}, - }, -} - -// base contains precomputed multiples of the base-point. See the Ed25519 paper -// for a discussion about how these values are used. -var base = [32][8]PreComputedGroupElement{ - { - { - FieldElement{25967493, -14356035, 29566456, 3660896, -12694345, 4014787, 27544626, -11754271, -6079156, 2047605}, - FieldElement{-12545711, 934262, -2722910, 3049990, -727428, 9406986, 12720692, 5043384, 19500929, -15469378}, - FieldElement{-8738181, 4489570, 9688441, -14785194, 10184609, -12363380, 29287919, 11864899, -24514362, -4438546}, - }, - { - FieldElement{-12815894, -12976347, -21581243, 11784320, -25355658, -2750717, -11717903, -3814571, -358445, -10211303}, - FieldElement{-21703237, 6903825, 27185491, 6451973, -29577724, -9554005, -15616551, 11189268, -26829678, -5319081}, - FieldElement{26966642, 11152617, 32442495, 15396054, 14353839, -12752335, -3128826, -9541118, -15472047, -4166697}, - }, - { - FieldElement{15636291, -9688557, 24204773, -7912398, 616977, -16685262, 27787600, -14772189, 28944400, -1550024}, - FieldElement{16568933, 4717097, -11556148, -1102322, 15682896, -11807043, 16354577, -11775962, 7689662, 11199574}, - FieldElement{30464156, -5976125, -11779434, -15670865, 23220365, 15915852, 7512774, 10017326, -17749093, -9920357}, - }, - { - FieldElement{-17036878, 13921892, 10945806, -6033431, 27105052, -16084379, -28926210, 15006023, 3284568, -6276540}, - FieldElement{23599295, -8306047, -11193664, -7687416, 13236774, 10506355, 7464579, 9656445, 13059162, 10374397}, - FieldElement{7798556, 16710257, 3033922, 2874086, 28997861, 2835604, 32406664, -3839045, -641708, -101325}, - }, - { - FieldElement{10861363, 11473154, 27284546, 1981175, -30064349, 12577861, 32867885, 14515107, -15438304, 10819380}, - FieldElement{4708026, 6336745, 20377586, 9066809, -11272109, 6594696, -25653668, 12483688, -12668491, 5581306}, - FieldElement{19563160, 16186464, -29386857, 4097519, 10237984, -4348115, 28542350, 13850243, -23678021, -15815942}, - }, - { - FieldElement{-15371964, -12862754, 32573250, 4720197, -26436522, 5875511, -19188627, -15224819, -9818940, -12085777}, - FieldElement{-8549212, 109983, 15149363, 2178705, 22900618, 4543417, 3044240, -15689887, 1762328, 14866737}, - FieldElement{-18199695, -15951423, -10473290, 1707278, -17185920, 3916101, -28236412, 3959421, 27914454, 4383652}, - }, - { - FieldElement{5153746, 9909285, 1723747, -2777874, 30523605, 5516873, 19480852, 5230134, -23952439, -15175766}, - FieldElement{-30269007, -3463509, 7665486, 10083793, 28475525, 1649722, 20654025, 16520125, 30598449, 7715701}, - FieldElement{28881845, 14381568, 9657904, 3680757, -20181635, 7843316, -31400660, 1370708, 29794553, -1409300}, - }, - { - FieldElement{14499471, -2729599, -33191113, -4254652, 28494862, 14271267, 30290735, 10876454, -33154098, 2381726}, - FieldElement{-7195431, -2655363, -14730155, 462251, -27724326, 3941372, -6236617, 3696005, -32300832, 15351955}, - FieldElement{27431194, 8222322, 16448760, -3907995, -18707002, 11938355, -32961401, -2970515, 29551813, 10109425}, - }, - }, - { - { - FieldElement{-13657040, -13155431, -31283750, 11777098, 21447386, 6519384, -2378284, -1627556, 10092783, -4764171}, - FieldElement{27939166, 14210322, 4677035, 16277044, -22964462, -12398139, -32508754, 12005538, -17810127, 12803510}, - FieldElement{17228999, -15661624, -1233527, 300140, -1224870, -11714777, 30364213, -9038194, 18016357, 4397660}, - }, - { - FieldElement{-10958843, -7690207, 4776341, -14954238, 27850028, -15602212, -26619106, 14544525, -17477504, 982639}, - FieldElement{29253598, 15796703, -2863982, -9908884, 10057023, 3163536, 7332899, -4120128, -21047696, 9934963}, - FieldElement{5793303, 16271923, -24131614, -10116404, 29188560, 1206517, -14747930, 4559895, -30123922, -10897950}, - }, - { - FieldElement{-27643952, -11493006, 16282657, -11036493, 28414021, -15012264, 24191034, 4541697, -13338309, 5500568}, - FieldElement{12650548, -1497113, 9052871, 11355358, -17680037, -8400164, -17430592, 12264343, 10874051, 13524335}, - FieldElement{25556948, -3045990, 714651, 2510400, 23394682, -10415330, 33119038, 5080568, -22528059, 5376628}, - }, - { - FieldElement{-26088264, -4011052, -17013699, -3537628, -6726793, 1920897, -22321305, -9447443, 4535768, 1569007}, - FieldElement{-2255422, 14606630, -21692440, -8039818, 28430649, 8775819, -30494562, 3044290, 31848280, 12543772}, - FieldElement{-22028579, 2943893, -31857513, 6777306, 13784462, -4292203, -27377195, -2062731, 7718482, 14474653}, - }, - { - FieldElement{2385315, 2454213, -22631320, 46603, -4437935, -15680415, 656965, -7236665, 24316168, -5253567}, - FieldElement{13741529, 10911568, -33233417, -8603737, -20177830, -1033297, 33040651, -13424532, -20729456, 8321686}, - FieldElement{21060490, -2212744, 15712757, -4336099, 1639040, 10656336, 23845965, -11874838, -9984458, 608372}, - }, - { - FieldElement{-13672732, -15087586, -10889693, -7557059, -6036909, 11305547, 1123968, -6780577, 27229399, 23887}, - FieldElement{-23244140, -294205, -11744728, 14712571, -29465699, -2029617, 12797024, -6440308, -1633405, 16678954}, - FieldElement{-29500620, 4770662, -16054387, 14001338, 7830047, 9564805, -1508144, -4795045, -17169265, 4904953}, - }, - { - FieldElement{24059557, 14617003, 19037157, -15039908, 19766093, -14906429, 5169211, 16191880, 2128236, -4326833}, - FieldElement{-16981152, 4124966, -8540610, -10653797, 30336522, -14105247, -29806336, 916033, -6882542, -2986532}, - FieldElement{-22630907, 12419372, -7134229, -7473371, -16478904, 16739175, 285431, 2763829, 15736322, 4143876}, - }, - { - FieldElement{2379352, 11839345, -4110402, -5988665, 11274298, 794957, 212801, -14594663, 23527084, -16458268}, - FieldElement{33431127, -11130478, -17838966, -15626900, 8909499, 8376530, -32625340, 4087881, -15188911, -14416214}, - FieldElement{1767683, 7197987, -13205226, -2022635, -13091350, 448826, 5799055, 4357868, -4774191, -16323038}, - }, - }, - { - { - FieldElement{6721966, 13833823, -23523388, -1551314, 26354293, -11863321, 23365147, -3949732, 7390890, 2759800}, - FieldElement{4409041, 2052381, 23373853, 10530217, 7676779, -12885954, 21302353, -4264057, 1244380, -12919645}, - FieldElement{-4421239, 7169619, 4982368, -2957590, 30256825, -2777540, 14086413, 9208236, 15886429, 16489664}, - }, - { - FieldElement{1996075, 10375649, 14346367, 13311202, -6874135, -16438411, -13693198, 398369, -30606455, -712933}, - FieldElement{-25307465, 9795880, -2777414, 14878809, -33531835, 14780363, 13348553, 12076947, -30836462, 5113182}, - FieldElement{-17770784, 11797796, 31950843, 13929123, -25888302, 12288344, -30341101, -7336386, 13847711, 5387222}, - }, - { - FieldElement{-18582163, -3416217, 17824843, -2340966, 22744343, -10442611, 8763061, 3617786, -19600662, 10370991}, - FieldElement{20246567, -14369378, 22358229, -543712, 18507283, -10413996, 14554437, -8746092, 32232924, 16763880}, - FieldElement{9648505, 10094563, 26416693, 14745928, -30374318, -6472621, 11094161, 15689506, 3140038, -16510092}, - }, - { - FieldElement{-16160072, 5472695, 31895588, 4744994, 8823515, 10365685, -27224800, 9448613, -28774454, 366295}, - FieldElement{19153450, 11523972, -11096490, -6503142, -24647631, 5420647, 28344573, 8041113, 719605, 11671788}, - FieldElement{8678025, 2694440, -6808014, 2517372, 4964326, 11152271, -15432916, -15266516, 27000813, -10195553}, - }, - { - FieldElement{-15157904, 7134312, 8639287, -2814877, -7235688, 10421742, 564065, 5336097, 6750977, -14521026}, - FieldElement{11836410, -3979488, 26297894, 16080799, 23455045, 15735944, 1695823, -8819122, 8169720, 16220347}, - FieldElement{-18115838, 8653647, 17578566, -6092619, -8025777, -16012763, -11144307, -2627664, -5990708, -14166033}, - }, - { - FieldElement{-23308498, -10968312, 15213228, -10081214, -30853605, -11050004, 27884329, 2847284, 2655861, 1738395}, - FieldElement{-27537433, -14253021, -25336301, -8002780, -9370762, 8129821, 21651608, -3239336, -19087449, -11005278}, - FieldElement{1533110, 3437855, 23735889, 459276, 29970501, 11335377, 26030092, 5821408, 10478196, 8544890}, - }, - { - FieldElement{32173121, -16129311, 24896207, 3921497, 22579056, -3410854, 19270449, 12217473, 17789017, -3395995}, - FieldElement{-30552961, -2228401, -15578829, -10147201, 13243889, 517024, 15479401, -3853233, 30460520, 1052596}, - FieldElement{-11614875, 13323618, 32618793, 8175907, -15230173, 12596687, 27491595, -4612359, 3179268, -9478891}, - }, - { - FieldElement{31947069, -14366651, -4640583, -15339921, -15125977, -6039709, -14756777, -16411740, 19072640, -9511060}, - FieldElement{11685058, 11822410, 3158003, -13952594, 33402194, -4165066, 5977896, -5215017, 473099, 5040608}, - FieldElement{-20290863, 8198642, -27410132, 11602123, 1290375, -2799760, 28326862, 1721092, -19558642, -3131606}, - }, - }, - { - { - FieldElement{7881532, 10687937, 7578723, 7738378, -18951012, -2553952, 21820786, 8076149, -27868496, 11538389}, - FieldElement{-19935666, 3899861, 18283497, -6801568, -15728660, -11249211, 8754525, 7446702, -5676054, 5797016}, - FieldElement{-11295600, -3793569, -15782110, -7964573, 12708869, -8456199, 2014099, -9050574, -2369172, -5877341}, - }, - { - FieldElement{-22472376, -11568741, -27682020, 1146375, 18956691, 16640559, 1192730, -3714199, 15123619, 10811505}, - FieldElement{14352098, -3419715, -18942044, 10822655, 32750596, 4699007, -70363, 15776356, -28886779, -11974553}, - FieldElement{-28241164, -8072475, -4978962, -5315317, 29416931, 1847569, -20654173, -16484855, 4714547, -9600655}, - }, - { - FieldElement{15200332, 8368572, 19679101, 15970074, -31872674, 1959451, 24611599, -4543832, -11745876, 12340220}, - FieldElement{12876937, -10480056, 33134381, 6590940, -6307776, 14872440, 9613953, 8241152, 15370987, 9608631}, - FieldElement{-4143277, -12014408, 8446281, -391603, 4407738, 13629032, -7724868, 15866074, -28210621, -8814099}, - }, - { - FieldElement{26660628, -15677655, 8393734, 358047, -7401291, 992988, -23904233, 858697, 20571223, 8420556}, - FieldElement{14620715, 13067227, -15447274, 8264467, 14106269, 15080814, 33531827, 12516406, -21574435, -12476749}, - FieldElement{236881, 10476226, 57258, -14677024, 6472998, 2466984, 17258519, 7256740, 8791136, 15069930}, - }, - { - FieldElement{1276410, -9371918, 22949635, -16322807, -23493039, -5702186, 14711875, 4874229, -30663140, -2331391}, - FieldElement{5855666, 4990204, -13711848, 7294284, -7804282, 1924647, -1423175, -7912378, -33069337, 9234253}, - FieldElement{20590503, -9018988, 31529744, -7352666, -2706834, 10650548, 31559055, -11609587, 18979186, 13396066}, - }, - { - FieldElement{24474287, 4968103, 22267082, 4407354, 24063882, -8325180, -18816887, 13594782, 33514650, 7021958}, - FieldElement{-11566906, -6565505, -21365085, 15928892, -26158305, 4315421, -25948728, -3916677, -21480480, 12868082}, - FieldElement{-28635013, 13504661, 19988037, -2132761, 21078225, 6443208, -21446107, 2244500, -12455797, -8089383}, - }, - { - FieldElement{-30595528, 13793479, -5852820, 319136, -25723172, -6263899, 33086546, 8957937, -15233648, 5540521}, - FieldElement{-11630176, -11503902, -8119500, -7643073, 2620056, 1022908, -23710744, -1568984, -16128528, -14962807}, - FieldElement{23152971, 775386, 27395463, 14006635, -9701118, 4649512, 1689819, 892185, -11513277, -15205948}, - }, - { - FieldElement{9770129, 9586738, 26496094, 4324120, 1556511, -3550024, 27453819, 4763127, -19179614, 5867134}, - FieldElement{-32765025, 1927590, 31726409, -4753295, 23962434, -16019500, 27846559, 5931263, -29749703, -16108455}, - FieldElement{27461885, -2977536, 22380810, 1815854, -23033753, -3031938, 7283490, -15148073, -19526700, 7734629}, - }, - }, - { - { - FieldElement{-8010264, -9590817, -11120403, 6196038, 29344158, -13430885, 7585295, -3176626, 18549497, 15302069}, - FieldElement{-32658337, -6171222, -7672793, -11051681, 6258878, 13504381, 10458790, -6418461, -8872242, 8424746}, - FieldElement{24687205, 8613276, -30667046, -3233545, 1863892, -1830544, 19206234, 7134917, -11284482, -828919}, - }, - { - FieldElement{11334899, -9218022, 8025293, 12707519, 17523892, -10476071, 10243738, -14685461, -5066034, 16498837}, - FieldElement{8911542, 6887158, -9584260, -6958590, 11145641, -9543680, 17303925, -14124238, 6536641, 10543906}, - FieldElement{-28946384, 15479763, -17466835, 568876, -1497683, 11223454, -2669190, -16625574, -27235709, 8876771}, - }, - { - FieldElement{-25742899, -12566864, -15649966, -846607, -33026686, -796288, -33481822, 15824474, -604426, -9039817}, - FieldElement{10330056, 70051, 7957388, -9002667, 9764902, 15609756, 27698697, -4890037, 1657394, 3084098}, - FieldElement{10477963, -7470260, 12119566, -13250805, 29016247, -5365589, 31280319, 14396151, -30233575, 15272409}, - }, - { - FieldElement{-12288309, 3169463, 28813183, 16658753, 25116432, -5630466, -25173957, -12636138, -25014757, 1950504}, - FieldElement{-26180358, 9489187, 11053416, -14746161, -31053720, 5825630, -8384306, -8767532, 15341279, 8373727}, - FieldElement{28685821, 7759505, -14378516, -12002860, -31971820, 4079242, 298136, -10232602, -2878207, 15190420}, - }, - { - FieldElement{-32932876, 13806336, -14337485, -15794431, -24004620, 10940928, 8669718, 2742393, -26033313, -6875003}, - FieldElement{-1580388, -11729417, -25979658, -11445023, -17411874, -10912854, 9291594, -16247779, -12154742, 6048605}, - FieldElement{-30305315, 14843444, 1539301, 11864366, 20201677, 1900163, 13934231, 5128323, 11213262, 9168384}, - }, - { - FieldElement{-26280513, 11007847, 19408960, -940758, -18592965, -4328580, -5088060, -11105150, 20470157, -16398701}, - FieldElement{-23136053, 9282192, 14855179, -15390078, -7362815, -14408560, -22783952, 14461608, 14042978, 5230683}, - FieldElement{29969567, -2741594, -16711867, -8552442, 9175486, -2468974, 21556951, 3506042, -5933891, -12449708}, - }, - { - FieldElement{-3144746, 8744661, 19704003, 4581278, -20430686, 6830683, -21284170, 8971513, -28539189, 15326563}, - FieldElement{-19464629, 10110288, -17262528, -3503892, -23500387, 1355669, -15523050, 15300988, -20514118, 9168260}, - FieldElement{-5353335, 4488613, -23803248, 16314347, 7780487, -15638939, -28948358, 9601605, 33087103, -9011387}, - }, - { - FieldElement{-19443170, -15512900, -20797467, -12445323, -29824447, 10229461, -27444329, -15000531, -5996870, 15664672}, - FieldElement{23294591, -16632613, -22650781, -8470978, 27844204, 11461195, 13099750, -2460356, 18151676, 13417686}, - FieldElement{-24722913, -4176517, -31150679, 5988919, -26858785, 6685065, 1661597, -12551441, 15271676, -15452665}, - }, - }, - { - { - FieldElement{11433042, -13228665, 8239631, -5279517, -1985436, -725718, -18698764, 2167544, -6921301, -13440182}, - FieldElement{-31436171, 15575146, 30436815, 12192228, -22463353, 9395379, -9917708, -8638997, 12215110, 12028277}, - FieldElement{14098400, 6555944, 23007258, 5757252, -15427832, -12950502, 30123440, 4617780, -16900089, -655628}, - }, - { - FieldElement{-4026201, -15240835, 11893168, 13718664, -14809462, 1847385, -15819999, 10154009, 23973261, -12684474}, - FieldElement{-26531820, -3695990, -1908898, 2534301, -31870557, -16550355, 18341390, -11419951, 32013174, -10103539}, - FieldElement{-25479301, 10876443, -11771086, -14625140, -12369567, 1838104, 21911214, 6354752, 4425632, -837822}, - }, - { - FieldElement{-10433389, -14612966, 22229858, -3091047, -13191166, 776729, -17415375, -12020462, 4725005, 14044970}, - FieldElement{19268650, -7304421, 1555349, 8692754, -21474059, -9910664, 6347390, -1411784, -19522291, -16109756}, - FieldElement{-24864089, 12986008, -10898878, -5558584, -11312371, -148526, 19541418, 8180106, 9282262, 10282508}, - }, - { - FieldElement{-26205082, 4428547, -8661196, -13194263, 4098402, -14165257, 15522535, 8372215, 5542595, -10702683}, - FieldElement{-10562541, 14895633, 26814552, -16673850, -17480754, -2489360, -2781891, 6993761, -18093885, 10114655}, - FieldElement{-20107055, -929418, 31422704, 10427861, -7110749, 6150669, -29091755, -11529146, 25953725, -106158}, - }, - { - FieldElement{-4234397, -8039292, -9119125, 3046000, 2101609, -12607294, 19390020, 6094296, -3315279, 12831125}, - FieldElement{-15998678, 7578152, 5310217, 14408357, -33548620, -224739, 31575954, 6326196, 7381791, -2421839}, - FieldElement{-20902779, 3296811, 24736065, -16328389, 18374254, 7318640, 6295303, 8082724, -15362489, 12339664}, - }, - { - FieldElement{27724736, 2291157, 6088201, -14184798, 1792727, 5857634, 13848414, 15768922, 25091167, 14856294}, - FieldElement{-18866652, 8331043, 24373479, 8541013, -701998, -9269457, 12927300, -12695493, -22182473, -9012899}, - FieldElement{-11423429, -5421590, 11632845, 3405020, 30536730, -11674039, -27260765, 13866390, 30146206, 9142070}, - }, - { - FieldElement{3924129, -15307516, -13817122, -10054960, 12291820, -668366, -27702774, 9326384, -8237858, 4171294}, - FieldElement{-15921940, 16037937, 6713787, 16606682, -21612135, 2790944, 26396185, 3731949, 345228, -5462949}, - FieldElement{-21327538, 13448259, 25284571, 1143661, 20614966, -8849387, 2031539, -12391231, -16253183, -13582083}, - }, - { - FieldElement{31016211, -16722429, 26371392, -14451233, -5027349, 14854137, 17477601, 3842657, 28012650, -16405420}, - FieldElement{-5075835, 9368966, -8562079, -4600902, -15249953, 6970560, -9189873, 16292057, -8867157, 3507940}, - FieldElement{29439664, 3537914, 23333589, 6997794, -17555561, -11018068, -15209202, -15051267, -9164929, 6580396}, - }, - }, - { - { - FieldElement{-12185861, -7679788, 16438269, 10826160, -8696817, -6235611, 17860444, -9273846, -2095802, 9304567}, - FieldElement{20714564, -4336911, 29088195, 7406487, 11426967, -5095705, 14792667, -14608617, 5289421, -477127}, - FieldElement{-16665533, -10650790, -6160345, -13305760, 9192020, -1802462, 17271490, 12349094, 26939669, -3752294}, - }, - { - FieldElement{-12889898, 9373458, 31595848, 16374215, 21471720, 13221525, -27283495, -12348559, -3698806, 117887}, - FieldElement{22263325, -6560050, 3984570, -11174646, -15114008, -566785, 28311253, 5358056, -23319780, 541964}, - FieldElement{16259219, 3261970, 2309254, -15534474, -16885711, -4581916, 24134070, -16705829, -13337066, -13552195}, - }, - { - FieldElement{9378160, -13140186, -22845982, -12745264, 28198281, -7244098, -2399684, -717351, 690426, 14876244}, - FieldElement{24977353, -314384, -8223969, -13465086, 28432343, -1176353, -13068804, -12297348, -22380984, 6618999}, - FieldElement{-1538174, 11685646, 12944378, 13682314, -24389511, -14413193, 8044829, -13817328, 32239829, -5652762}, - }, - { - FieldElement{-18603066, 4762990, -926250, 8885304, -28412480, -3187315, 9781647, -10350059, 32779359, 5095274}, - FieldElement{-33008130, -5214506, -32264887, -3685216, 9460461, -9327423, -24601656, 14506724, 21639561, -2630236}, - FieldElement{-16400943, -13112215, 25239338, 15531969, 3987758, -4499318, -1289502, -6863535, 17874574, 558605}, - }, - { - FieldElement{-13600129, 10240081, 9171883, 16131053, -20869254, 9599700, 33499487, 5080151, 2085892, 5119761}, - FieldElement{-22205145, -2519528, -16381601, 414691, -25019550, 2170430, 30634760, -8363614, -31999993, -5759884}, - FieldElement{-6845704, 15791202, 8550074, -1312654, 29928809, -12092256, 27534430, -7192145, -22351378, 12961482}, - }, - { - FieldElement{-24492060, -9570771, 10368194, 11582341, -23397293, -2245287, 16533930, 8206996, -30194652, -5159638}, - FieldElement{-11121496, -3382234, 2307366, 6362031, -135455, 8868177, -16835630, 7031275, 7589640, 8945490}, - FieldElement{-32152748, 8917967, 6661220, -11677616, -1192060, -15793393, 7251489, -11182180, 24099109, -14456170}, - }, - { - FieldElement{5019558, -7907470, 4244127, -14714356, -26933272, 6453165, -19118182, -13289025, -6231896, -10280736}, - FieldElement{10853594, 10721687, 26480089, 5861829, -22995819, 1972175, -1866647, -10557898, -3363451, -6441124}, - FieldElement{-17002408, 5906790, 221599, -6563147, 7828208, -13248918, 24362661, -2008168, -13866408, 7421392}, - }, - { - FieldElement{8139927, -6546497, 32257646, -5890546, 30375719, 1886181, -21175108, 15441252, 28826358, -4123029}, - FieldElement{6267086, 9695052, 7709135, -16603597, -32869068, -1886135, 14795160, -7840124, 13746021, -1742048}, - FieldElement{28584902, 7787108, -6732942, -15050729, 22846041, -7571236, -3181936, -363524, 4771362, -8419958}, - }, - }, - { - { - FieldElement{24949256, 6376279, -27466481, -8174608, -18646154, -9930606, 33543569, -12141695, 3569627, 11342593}, - FieldElement{26514989, 4740088, 27912651, 3697550, 19331575, -11472339, 6809886, 4608608, 7325975, -14801071}, - FieldElement{-11618399, -14554430, -24321212, 7655128, -1369274, 5214312, -27400540, 10258390, -17646694, -8186692}, - }, - { - FieldElement{11431204, 15823007, 26570245, 14329124, 18029990, 4796082, -31446179, 15580664, 9280358, -3973687}, - FieldElement{-160783, -10326257, -22855316, -4304997, -20861367, -13621002, -32810901, -11181622, -15545091, 4387441}, - FieldElement{-20799378, 12194512, 3937617, -5805892, -27154820, 9340370, -24513992, 8548137, 20617071, -7482001}, - }, - { - FieldElement{-938825, -3930586, -8714311, 16124718, 24603125, -6225393, -13775352, -11875822, 24345683, 10325460}, - FieldElement{-19855277, -1568885, -22202708, 8714034, 14007766, 6928528, 16318175, -1010689, 4766743, 3552007}, - FieldElement{-21751364, -16730916, 1351763, -803421, -4009670, 3950935, 3217514, 14481909, 10988822, -3994762}, - }, - { - FieldElement{15564307, -14311570, 3101243, 5684148, 30446780, -8051356, 12677127, -6505343, -8295852, 13296005}, - FieldElement{-9442290, 6624296, -30298964, -11913677, -4670981, -2057379, 31521204, 9614054, -30000824, 12074674}, - FieldElement{4771191, -135239, 14290749, -13089852, 27992298, 14998318, -1413936, -1556716, 29832613, -16391035}, - }, - { - FieldElement{7064884, -7541174, -19161962, -5067537, -18891269, -2912736, 25825242, 5293297, -27122660, 13101590}, - FieldElement{-2298563, 2439670, -7466610, 1719965, -27267541, -16328445, 32512469, -5317593, -30356070, -4190957}, - FieldElement{-30006540, 10162316, -33180176, 3981723, -16482138, -13070044, 14413974, 9515896, 19568978, 9628812}, - }, - { - FieldElement{33053803, 199357, 15894591, 1583059, 27380243, -4580435, -17838894, -6106839, -6291786, 3437740}, - FieldElement{-18978877, 3884493, 19469877, 12726490, 15913552, 13614290, -22961733, 70104, 7463304, 4176122}, - FieldElement{-27124001, 10659917, 11482427, -16070381, 12771467, -6635117, -32719404, -5322751, 24216882, 5944158}, - }, - { - FieldElement{8894125, 7450974, -2664149, -9765752, -28080517, -12389115, 19345746, 14680796, 11632993, 5847885}, - FieldElement{26942781, -2315317, 9129564, -4906607, 26024105, 11769399, -11518837, 6367194, -9727230, 4782140}, - FieldElement{19916461, -4828410, -22910704, -11414391, 25606324, -5972441, 33253853, 8220911, 6358847, -1873857}, - }, - { - FieldElement{801428, -2081702, 16569428, 11065167, 29875704, 96627, 7908388, -4480480, -13538503, 1387155}, - FieldElement{19646058, 5720633, -11416706, 12814209, 11607948, 12749789, 14147075, 15156355, -21866831, 11835260}, - FieldElement{19299512, 1155910, 28703737, 14890794, 2925026, 7269399, 26121523, 15467869, -26560550, 5052483}, - }, - }, - { - { - FieldElement{-3017432, 10058206, 1980837, 3964243, 22160966, 12322533, -6431123, -12618185, 12228557, -7003677}, - FieldElement{32944382, 14922211, -22844894, 5188528, 21913450, -8719943, 4001465, 13238564, -6114803, 8653815}, - FieldElement{22865569, -4652735, 27603668, -12545395, 14348958, 8234005, 24808405, 5719875, 28483275, 2841751}, - }, - { - FieldElement{-16420968, -1113305, -327719, -12107856, 21886282, -15552774, -1887966, -315658, 19932058, -12739203}, - FieldElement{-11656086, 10087521, -8864888, -5536143, -19278573, -3055912, 3999228, 13239134, -4777469, -13910208}, - FieldElement{1382174, -11694719, 17266790, 9194690, -13324356, 9720081, 20403944, 11284705, -14013818, 3093230}, - }, - { - FieldElement{16650921, -11037932, -1064178, 1570629, -8329746, 7352753, -302424, 16271225, -24049421, -6691850}, - FieldElement{-21911077, -5927941, -4611316, -5560156, -31744103, -10785293, 24123614, 15193618, -21652117, -16739389}, - FieldElement{-9935934, -4289447, -25279823, 4372842, 2087473, 10399484, 31870908, 14690798, 17361620, 11864968}, - }, - { - FieldElement{-11307610, 6210372, 13206574, 5806320, -29017692, -13967200, -12331205, -7486601, -25578460, -16240689}, - FieldElement{14668462, -12270235, 26039039, 15305210, 25515617, 4542480, 10453892, 6577524, 9145645, -6443880}, - FieldElement{5974874, 3053895, -9433049, -10385191, -31865124, 3225009, -7972642, 3936128, -5652273, -3050304}, - }, - { - FieldElement{30625386, -4729400, -25555961, -12792866, -20484575, 7695099, 17097188, -16303496, -27999779, 1803632}, - FieldElement{-3553091, 9865099, -5228566, 4272701, -5673832, -16689700, 14911344, 12196514, -21405489, 7047412}, - FieldElement{20093277, 9920966, -11138194, -5343857, 13161587, 12044805, -32856851, 4124601, -32343828, -10257566}, - }, - { - FieldElement{-20788824, 14084654, -13531713, 7842147, 19119038, -13822605, 4752377, -8714640, -21679658, 2288038}, - FieldElement{-26819236, -3283715, 29965059, 3039786, -14473765, 2540457, 29457502, 14625692, -24819617, 12570232}, - FieldElement{-1063558, -11551823, 16920318, 12494842, 1278292, -5869109, -21159943, -3498680, -11974704, 4724943}, - }, - { - FieldElement{17960970, -11775534, -4140968, -9702530, -8876562, -1410617, -12907383, -8659932, -29576300, 1903856}, - FieldElement{23134274, -14279132, -10681997, -1611936, 20684485, 15770816, -12989750, 3190296, 26955097, 14109738}, - FieldElement{15308788, 5320727, -30113809, -14318877, 22902008, 7767164, 29425325, -11277562, 31960942, 11934971}, - }, - { - FieldElement{-27395711, 8435796, 4109644, 12222639, -24627868, 14818669, 20638173, 4875028, 10491392, 1379718}, - FieldElement{-13159415, 9197841, 3875503, -8936108, -1383712, -5879801, 33518459, 16176658, 21432314, 12180697}, - FieldElement{-11787308, 11500838, 13787581, -13832590, -22430679, 10140205, 1465425, 12689540, -10301319, -13872883}, - }, - }, - { - { - FieldElement{5414091, -15386041, -21007664, 9643570, 12834970, 1186149, -2622916, -1342231, 26128231, 6032912}, - FieldElement{-26337395, -13766162, 32496025, -13653919, 17847801, -12669156, 3604025, 8316894, -25875034, -10437358}, - FieldElement{3296484, 6223048, 24680646, -12246460, -23052020, 5903205, -8862297, -4639164, 12376617, 3188849}, - }, - { - FieldElement{29190488, -14659046, 27549113, -1183516, 3520066, -10697301, 32049515, -7309113, -16109234, -9852307}, - FieldElement{-14744486, -9309156, 735818, -598978, -20407687, -5057904, 25246078, -15795669, 18640741, -960977}, - FieldElement{-6928835, -16430795, 10361374, 5642961, 4910474, 12345252, -31638386, -494430, 10530747, 1053335}, - }, - { - FieldElement{-29265967, -14186805, -13538216, -12117373, -19457059, -10655384, -31462369, -2948985, 24018831, 15026644}, - FieldElement{-22592535, -3145277, -2289276, 5953843, -13440189, 9425631, 25310643, 13003497, -2314791, -15145616}, - FieldElement{-27419985, -603321, -8043984, -1669117, -26092265, 13987819, -27297622, 187899, -23166419, -2531735}, - }, - { - FieldElement{-21744398, -13810475, 1844840, 5021428, -10434399, -15911473, 9716667, 16266922, -5070217, 726099}, - FieldElement{29370922, -6053998, 7334071, -15342259, 9385287, 2247707, -13661962, -4839461, 30007388, -15823341}, - FieldElement{-936379, 16086691, 23751945, -543318, -1167538, -5189036, 9137109, 730663, 9835848, 4555336}, - }, - { - FieldElement{-23376435, 1410446, -22253753, -12899614, 30867635, 15826977, 17693930, 544696, -11985298, 12422646}, - FieldElement{31117226, -12215734, -13502838, 6561947, -9876867, -12757670, -5118685, -4096706, 29120153, 13924425}, - FieldElement{-17400879, -14233209, 19675799, -2734756, -11006962, -5858820, -9383939, -11317700, 7240931, -237388}, - }, - { - FieldElement{-31361739, -11346780, -15007447, -5856218, -22453340, -12152771, 1222336, 4389483, 3293637, -15551743}, - FieldElement{-16684801, -14444245, 11038544, 11054958, -13801175, -3338533, -24319580, 7733547, 12796905, -6335822}, - FieldElement{-8759414, -10817836, -25418864, 10783769, -30615557, -9746811, -28253339, 3647836, 3222231, -11160462}, - }, - { - FieldElement{18606113, 1693100, -25448386, -15170272, 4112353, 10045021, 23603893, -2048234, -7550776, 2484985}, - FieldElement{9255317, -3131197, -12156162, -1004256, 13098013, -9214866, 16377220, -2102812, -19802075, -3034702}, - FieldElement{-22729289, 7496160, -5742199, 11329249, 19991973, -3347502, -31718148, 9936966, -30097688, -10618797}, - }, - { - FieldElement{21878590, -5001297, 4338336, 13643897, -3036865, 13160960, 19708896, 5415497, -7360503, -4109293}, - FieldElement{27736861, 10103576, 12500508, 8502413, -3413016, -9633558, 10436918, -1550276, -23659143, -8132100}, - FieldElement{19492550, -12104365, -29681976, -852630, -3208171, 12403437, 30066266, 8367329, 13243957, 8709688}, - }, - }, - { - { - FieldElement{12015105, 2801261, 28198131, 10151021, 24818120, -4743133, -11194191, -5645734, 5150968, 7274186}, - FieldElement{2831366, -12492146, 1478975, 6122054, 23825128, -12733586, 31097299, 6083058, 31021603, -9793610}, - FieldElement{-2529932, -2229646, 445613, 10720828, -13849527, -11505937, -23507731, 16354465, 15067285, -14147707}, - }, - { - FieldElement{7840942, 14037873, -33364863, 15934016, -728213, -3642706, 21403988, 1057586, -19379462, -12403220}, - FieldElement{915865, -16469274, 15608285, -8789130, -24357026, 6060030, -17371319, 8410997, -7220461, 16527025}, - FieldElement{32922597, -556987, 20336074, -16184568, 10903705, -5384487, 16957574, 52992, 23834301, 6588044}, - }, - { - FieldElement{32752030, 11232950, 3381995, -8714866, 22652988, -10744103, 17159699, 16689107, -20314580, -1305992}, - FieldElement{-4689649, 9166776, -25710296, -10847306, 11576752, 12733943, 7924251, -2752281, 1976123, -7249027}, - FieldElement{21251222, 16309901, -2983015, -6783122, 30810597, 12967303, 156041, -3371252, 12331345, -8237197}, - }, - { - FieldElement{8651614, -4477032, -16085636, -4996994, 13002507, 2950805, 29054427, -5106970, 10008136, -4667901}, - FieldElement{31486080, 15114593, -14261250, 12951354, 14369431, -7387845, 16347321, -13662089, 8684155, -10532952}, - FieldElement{19443825, 11385320, 24468943, -9659068, -23919258, 2187569, -26263207, -6086921, 31316348, 14219878}, - }, - { - FieldElement{-28594490, 1193785, 32245219, 11392485, 31092169, 15722801, 27146014, 6992409, 29126555, 9207390}, - FieldElement{32382935, 1110093, 18477781, 11028262, -27411763, -7548111, -4980517, 10843782, -7957600, -14435730}, - FieldElement{2814918, 7836403, 27519878, -7868156, -20894015, -11553689, -21494559, 8550130, 28346258, 1994730}, - }, - { - FieldElement{-19578299, 8085545, -14000519, -3948622, 2785838, -16231307, -19516951, 7174894, 22628102, 8115180}, - FieldElement{-30405132, 955511, -11133838, -15078069, -32447087, -13278079, -25651578, 3317160, -9943017, 930272}, - FieldElement{-15303681, -6833769, 28856490, 1357446, 23421993, 1057177, 24091212, -1388970, -22765376, -10650715}, - }, - { - FieldElement{-22751231, -5303997, -12907607, -12768866, -15811511, -7797053, -14839018, -16554220, -1867018, 8398970}, - FieldElement{-31969310, 2106403, -4736360, 1362501, 12813763, 16200670, 22981545, -6291273, 18009408, -15772772}, - FieldElement{-17220923, -9545221, -27784654, 14166835, 29815394, 7444469, 29551787, -3727419, 19288549, 1325865}, - }, - { - FieldElement{15100157, -15835752, -23923978, -1005098, -26450192, 15509408, 12376730, -3479146, 33166107, -8042750}, - FieldElement{20909231, 13023121, -9209752, 16251778, -5778415, -8094914, 12412151, 10018715, 2213263, -13878373}, - FieldElement{32529814, -11074689, 30361439, -16689753, -9135940, 1513226, 22922121, 6382134, -5766928, 8371348}, - }, - }, - { - { - FieldElement{9923462, 11271500, 12616794, 3544722, -29998368, -1721626, 12891687, -8193132, -26442943, 10486144}, - FieldElement{-22597207, -7012665, 8587003, -8257861, 4084309, -12970062, 361726, 2610596, -23921530, -11455195}, - FieldElement{5408411, -1136691, -4969122, 10561668, 24145918, 14240566, 31319731, -4235541, 19985175, -3436086}, - }, - { - FieldElement{-13994457, 16616821, 14549246, 3341099, 32155958, 13648976, -17577068, 8849297, 65030, 8370684}, - FieldElement{-8320926, -12049626, 31204563, 5839400, -20627288, -1057277, -19442942, 6922164, 12743482, -9800518}, - FieldElement{-2361371, 12678785, 28815050, 4759974, -23893047, 4884717, 23783145, 11038569, 18800704, 255233}, - }, - { - FieldElement{-5269658, -1773886, 13957886, 7990715, 23132995, 728773, 13393847, 9066957, 19258688, -14753793}, - FieldElement{-2936654, -10827535, -10432089, 14516793, -3640786, 4372541, -31934921, 2209390, -1524053, 2055794}, - FieldElement{580882, 16705327, 5468415, -2683018, -30926419, -14696000, -7203346, -8994389, -30021019, 7394435}, - }, - { - FieldElement{23838809, 1822728, -15738443, 15242727, 8318092, -3733104, -21672180, -3492205, -4821741, 14799921}, - FieldElement{13345610, 9759151, 3371034, -16137791, 16353039, 8577942, 31129804, 13496856, -9056018, 7402518}, - FieldElement{2286874, -4435931, -20042458, -2008336, -13696227, 5038122, 11006906, -15760352, 8205061, 1607563}, - }, - { - FieldElement{14414086, -8002132, 3331830, -3208217, 22249151, -5594188, 18364661, -2906958, 30019587, -9029278}, - FieldElement{-27688051, 1585953, -10775053, 931069, -29120221, -11002319, -14410829, 12029093, 9944378, 8024}, - FieldElement{4368715, -3709630, 29874200, -15022983, -20230386, -11410704, -16114594, -999085, -8142388, 5640030}, - }, - { - FieldElement{10299610, 13746483, 11661824, 16234854, 7630238, 5998374, 9809887, -16694564, 15219798, -14327783}, - FieldElement{27425505, -5719081, 3055006, 10660664, 23458024, 595578, -15398605, -1173195, -18342183, 9742717}, - FieldElement{6744077, 2427284, 26042789, 2720740, -847906, 1118974, 32324614, 7406442, 12420155, 1994844}, - }, - { - FieldElement{14012521, -5024720, -18384453, -9578469, -26485342, -3936439, -13033478, -10909803, 24319929, -6446333}, - FieldElement{16412690, -4507367, 10772641, 15929391, -17068788, -4658621, 10555945, -10484049, -30102368, -4739048}, - FieldElement{22397382, -7767684, -9293161, -12792868, 17166287, -9755136, -27333065, 6199366, 21880021, -12250760}, - }, - { - FieldElement{-4283307, 5368523, -31117018, 8163389, -30323063, 3209128, 16557151, 8890729, 8840445, 4957760}, - FieldElement{-15447727, 709327, -6919446, -10870178, -29777922, 6522332, -21720181, 12130072, -14796503, 5005757}, - FieldElement{-2114751, -14308128, 23019042, 15765735, -25269683, 6002752, 10183197, -13239326, -16395286, -2176112}, - }, - }, - { - { - FieldElement{-19025756, 1632005, 13466291, -7995100, -23640451, 16573537, -32013908, -3057104, 22208662, 2000468}, - FieldElement{3065073, -1412761, -25598674, -361432, -17683065, -5703415, -8164212, 11248527, -3691214, -7414184}, - FieldElement{10379208, -6045554, 8877319, 1473647, -29291284, -12507580, 16690915, 2553332, -3132688, 16400289}, - }, - { - FieldElement{15716668, 1254266, -18472690, 7446274, -8448918, 6344164, -22097271, -7285580, 26894937, 9132066}, - FieldElement{24158887, 12938817, 11085297, -8177598, -28063478, -4457083, -30576463, 64452, -6817084, -2692882}, - FieldElement{13488534, 7794716, 22236231, 5989356, 25426474, -12578208, 2350710, -3418511, -4688006, 2364226}, - }, - { - FieldElement{16335052, 9132434, 25640582, 6678888, 1725628, 8517937, -11807024, -11697457, 15445875, -7798101}, - FieldElement{29004207, -7867081, 28661402, -640412, -12794003, -7943086, 31863255, -4135540, -278050, -15759279}, - FieldElement{-6122061, -14866665, -28614905, 14569919, -10857999, -3591829, 10343412, -6976290, -29828287, -10815811}, - }, - { - FieldElement{27081650, 3463984, 14099042, -4517604, 1616303, -6205604, 29542636, 15372179, 17293797, 960709}, - FieldElement{20263915, 11434237, -5765435, 11236810, 13505955, -10857102, -16111345, 6493122, -19384511, 7639714}, - FieldElement{-2830798, -14839232, 25403038, -8215196, -8317012, -16173699, 18006287, -16043750, 29994677, -15808121}, - }, - { - FieldElement{9769828, 5202651, -24157398, -13631392, -28051003, -11561624, -24613141, -13860782, -31184575, 709464}, - FieldElement{12286395, 13076066, -21775189, -1176622, -25003198, 4057652, -32018128, -8890874, 16102007, 13205847}, - FieldElement{13733362, 5599946, 10557076, 3195751, -5557991, 8536970, -25540170, 8525972, 10151379, 10394400}, - }, - { - FieldElement{4024660, -16137551, 22436262, 12276534, -9099015, -2686099, 19698229, 11743039, -33302334, 8934414}, - FieldElement{-15879800, -4525240, -8580747, -2934061, 14634845, -698278, -9449077, 3137094, -11536886, 11721158}, - FieldElement{17555939, -5013938, 8268606, 2331751, -22738815, 9761013, 9319229, 8835153, -9205489, -1280045}, - }, - { - FieldElement{-461409, -7830014, 20614118, 16688288, -7514766, -4807119, 22300304, 505429, 6108462, -6183415}, - FieldElement{-5070281, 12367917, -30663534, 3234473, 32617080, -8422642, 29880583, -13483331, -26898490, -7867459}, - FieldElement{-31975283, 5726539, 26934134, 10237677, -3173717, -605053, 24199304, 3795095, 7592688, -14992079}, - }, - { - FieldElement{21594432, -14964228, 17466408, -4077222, 32537084, 2739898, 6407723, 12018833, -28256052, 4298412}, - FieldElement{-20650503, -11961496, -27236275, 570498, 3767144, -1717540, 13891942, -1569194, 13717174, 10805743}, - FieldElement{-14676630, -15644296, 15287174, 11927123, 24177847, -8175568, -796431, 14860609, -26938930, -5863836}, - }, - }, - { - { - FieldElement{12962541, 5311799, -10060768, 11658280, 18855286, -7954201, 13286263, -12808704, -4381056, 9882022}, - FieldElement{18512079, 11319350, -20123124, 15090309, 18818594, 5271736, -22727904, 3666879, -23967430, -3299429}, - FieldElement{-6789020, -3146043, 16192429, 13241070, 15898607, -14206114, -10084880, -6661110, -2403099, 5276065}, - }, - { - FieldElement{30169808, -5317648, 26306206, -11750859, 27814964, 7069267, 7152851, 3684982, 1449224, 13082861}, - FieldElement{10342826, 3098505, 2119311, 193222, 25702612, 12233820, 23697382, 15056736, -21016438, -8202000}, - FieldElement{-33150110, 3261608, 22745853, 7948688, 19370557, -15177665, -26171976, 6482814, -10300080, -11060101}, - }, - { - FieldElement{32869458, -5408545, 25609743, 15678670, -10687769, -15471071, 26112421, 2521008, -22664288, 6904815}, - FieldElement{29506923, 4457497, 3377935, -9796444, -30510046, 12935080, 1561737, 3841096, -29003639, -6657642}, - FieldElement{10340844, -6630377, -18656632, -2278430, 12621151, -13339055, 30878497, -11824370, -25584551, 5181966}, - }, - { - FieldElement{25940115, -12658025, 17324188, -10307374, -8671468, 15029094, 24396252, -16450922, -2322852, -12388574}, - FieldElement{-21765684, 9916823, -1300409, 4079498, -1028346, 11909559, 1782390, 12641087, 20603771, -6561742}, - FieldElement{-18882287, -11673380, 24849422, 11501709, 13161720, -4768874, 1925523, 11914390, 4662781, 7820689}, - }, - { - FieldElement{12241050, -425982, 8132691, 9393934, 32846760, -1599620, 29749456, 12172924, 16136752, 15264020}, - FieldElement{-10349955, -14680563, -8211979, 2330220, -17662549, -14545780, 10658213, 6671822, 19012087, 3772772}, - FieldElement{3753511, -3421066, 10617074, 2028709, 14841030, -6721664, 28718732, -15762884, 20527771, 12988982}, - }, - { - FieldElement{-14822485, -5797269, -3707987, 12689773, -898983, -10914866, -24183046, -10564943, 3299665, -12424953}, - FieldElement{-16777703, -15253301, -9642417, 4978983, 3308785, 8755439, 6943197, 6461331, -25583147, 8991218}, - FieldElement{-17226263, 1816362, -1673288, -6086439, 31783888, -8175991, -32948145, 7417950, -30242287, 1507265}, - }, - { - FieldElement{29692663, 6829891, -10498800, 4334896, 20945975, -11906496, -28887608, 8209391, 14606362, -10647073}, - FieldElement{-3481570, 8707081, 32188102, 5672294, 22096700, 1711240, -33020695, 9761487, 4170404, -2085325}, - FieldElement{-11587470, 14855945, -4127778, -1531857, -26649089, 15084046, 22186522, 16002000, -14276837, -8400798}, - }, - { - FieldElement{-4811456, 13761029, -31703877, -2483919, -3312471, 7869047, -7113572, -9620092, 13240845, 10965870}, - FieldElement{-7742563, -8256762, -14768334, -13656260, -23232383, 12387166, 4498947, 14147411, 29514390, 4302863}, - FieldElement{-13413405, -12407859, 20757302, -13801832, 14785143, 8976368, -5061276, -2144373, 17846988, -13971927}, - }, - }, - { - { - FieldElement{-2244452, -754728, -4597030, -1066309, -6247172, 1455299, -21647728, -9214789, -5222701, 12650267}, - FieldElement{-9906797, -16070310, 21134160, 12198166, -27064575, 708126, 387813, 13770293, -19134326, 10958663}, - FieldElement{22470984, 12369526, 23446014, -5441109, -21520802, -9698723, -11772496, -11574455, -25083830, 4271862}, - }, - { - FieldElement{-25169565, -10053642, -19909332, 15361595, -5984358, 2159192, 75375, -4278529, -32526221, 8469673}, - FieldElement{15854970, 4148314, -8893890, 7259002, 11666551, 13824734, -30531198, 2697372, 24154791, -9460943}, - FieldElement{15446137, -15806644, 29759747, 14019369, 30811221, -9610191, -31582008, 12840104, 24913809, 9815020}, - }, - { - FieldElement{-4709286, -5614269, -31841498, -12288893, -14443537, 10799414, -9103676, 13438769, 18735128, 9466238}, - FieldElement{11933045, 9281483, 5081055, -5183824, -2628162, -4905629, -7727821, -10896103, -22728655, 16199064}, - FieldElement{14576810, 379472, -26786533, -8317236, -29426508, -10812974, -102766, 1876699, 30801119, 2164795}, - }, - { - FieldElement{15995086, 3199873, 13672555, 13712240, -19378835, -4647646, -13081610, -15496269, -13492807, 1268052}, - FieldElement{-10290614, -3659039, -3286592, 10948818, 23037027, 3794475, -3470338, -12600221, -17055369, 3565904}, - FieldElement{29210088, -9419337, -5919792, -4952785, 10834811, -13327726, -16512102, -10820713, -27162222, -14030531}, - }, - { - FieldElement{-13161890, 15508588, 16663704, -8156150, -28349942, 9019123, -29183421, -3769423, 2244111, -14001979}, - FieldElement{-5152875, -3800936, -9306475, -6071583, 16243069, 14684434, -25673088, -16180800, 13491506, 4641841}, - FieldElement{10813417, 643330, -19188515, -728916, 30292062, -16600078, 27548447, -7721242, 14476989, -12767431}, - }, - { - FieldElement{10292079, 9984945, 6481436, 8279905, -7251514, 7032743, 27282937, -1644259, -27912810, 12651324}, - FieldElement{-31185513, -813383, 22271204, 11835308, 10201545, 15351028, 17099662, 3988035, 21721536, -3148940}, - FieldElement{10202177, -6545839, -31373232, -9574638, -32150642, -8119683, -12906320, 3852694, 13216206, 14842320}, - }, - { - FieldElement{-15815640, -10601066, -6538952, -7258995, -6984659, -6581778, -31500847, 13765824, -27434397, 9900184}, - FieldElement{14465505, -13833331, -32133984, -14738873, -27443187, 12990492, 33046193, 15796406, -7051866, -8040114}, - FieldElement{30924417, -8279620, 6359016, -12816335, 16508377, 9071735, -25488601, 15413635, 9524356, -7018878}, - }, - { - FieldElement{12274201, -13175547, 32627641, -1785326, 6736625, 13267305, 5237659, -5109483, 15663516, 4035784}, - FieldElement{-2951309, 8903985, 17349946, 601635, -16432815, -4612556, -13732739, -15889334, -22258478, 4659091}, - FieldElement{-16916263, -4952973, -30393711, -15158821, 20774812, 15897498, 5736189, 15026997, -2178256, -13455585}, - }, - }, - { - { - FieldElement{-8858980, -2219056, 28571666, -10155518, -474467, -10105698, -3801496, 278095, 23440562, -290208}, - FieldElement{10226241, -5928702, 15139956, 120818, -14867693, 5218603, 32937275, 11551483, -16571960, -7442864}, - FieldElement{17932739, -12437276, -24039557, 10749060, 11316803, 7535897, 22503767, 5561594, -3646624, 3898661}, - }, - { - FieldElement{7749907, -969567, -16339731, -16464, -25018111, 15122143, -1573531, 7152530, 21831162, 1245233}, - FieldElement{26958459, -14658026, 4314586, 8346991, -5677764, 11960072, -32589295, -620035, -30402091, -16716212}, - FieldElement{-12165896, 9166947, 33491384, 13673479, 29787085, 13096535, 6280834, 14587357, -22338025, 13987525}, - }, - { - FieldElement{-24349909, 7778775, 21116000, 15572597, -4833266, -5357778, -4300898, -5124639, -7469781, -2858068}, - FieldElement{9681908, -6737123, -31951644, 13591838, -6883821, 386950, 31622781, 6439245, -14581012, 4091397}, - FieldElement{-8426427, 1470727, -28109679, -1596990, 3978627, -5123623, -19622683, 12092163, 29077877, -14741988}, - }, - { - FieldElement{5269168, -6859726, -13230211, -8020715, 25932563, 1763552, -5606110, -5505881, -20017847, 2357889}, - FieldElement{32264008, -15407652, -5387735, -1160093, -2091322, -3946900, 23104804, -12869908, 5727338, 189038}, - FieldElement{14609123, -8954470, -6000566, -16622781, -14577387, -7743898, -26745169, 10942115, -25888931, -14884697}, - }, - { - FieldElement{20513500, 5557931, -15604613, 7829531, 26413943, -2019404, -21378968, 7471781, 13913677, -5137875}, - FieldElement{-25574376, 11967826, 29233242, 12948236, -6754465, 4713227, -8940970, 14059180, 12878652, 8511905}, - FieldElement{-25656801, 3393631, -2955415, -7075526, -2250709, 9366908, -30223418, 6812974, 5568676, -3127656}, - }, - { - FieldElement{11630004, 12144454, 2116339, 13606037, 27378885, 15676917, -17408753, -13504373, -14395196, 8070818}, - FieldElement{27117696, -10007378, -31282771, -5570088, 1127282, 12772488, -29845906, 10483306, -11552749, -1028714}, - FieldElement{10637467, -5688064, 5674781, 1072708, -26343588, -6982302, -1683975, 9177853, -27493162, 15431203}, - }, - { - FieldElement{20525145, 10892566, -12742472, 12779443, -29493034, 16150075, -28240519, 14943142, -15056790, -7935931}, - FieldElement{-30024462, 5626926, -551567, -9981087, 753598, 11981191, 25244767, -3239766, -3356550, 9594024}, - FieldElement{-23752644, 2636870, -5163910, -10103818, 585134, 7877383, 11345683, -6492290, 13352335, -10977084}, - }, - { - FieldElement{-1931799, -5407458, 3304649, -12884869, 17015806, -4877091, -29783850, -7752482, -13215537, -319204}, - FieldElement{20239939, 6607058, 6203985, 3483793, -18386976, -779229, -20723742, 15077870, -22750759, 14523817}, - FieldElement{27406042, -6041657, 27423596, -4497394, 4996214, 10002360, -28842031, -4545494, -30172742, -4805667}, - }, - }, - { - { - FieldElement{11374242, 12660715, 17861383, -12540833, 10935568, 1099227, -13886076, -9091740, -27727044, 11358504}, - FieldElement{-12730809, 10311867, 1510375, 10778093, -2119455, -9145702, 32676003, 11149336, -26123651, 4985768}, - FieldElement{-19096303, 341147, -6197485, -239033, 15756973, -8796662, -983043, 13794114, -19414307, -15621255}, - }, - { - FieldElement{6490081, 11940286, 25495923, -7726360, 8668373, -8751316, 3367603, 6970005, -1691065, -9004790}, - FieldElement{1656497, 13457317, 15370807, 6364910, 13605745, 8362338, -19174622, -5475723, -16796596, -5031438}, - FieldElement{-22273315, -13524424, -64685, -4334223, -18605636, -10921968, -20571065, -7007978, -99853, -10237333}, - }, - { - FieldElement{17747465, 10039260, 19368299, -4050591, -20630635, -16041286, 31992683, -15857976, -29260363, -5511971}, - FieldElement{31932027, -4986141, -19612382, 16366580, 22023614, 88450, 11371999, -3744247, 4882242, -10626905}, - FieldElement{29796507, 37186, 19818052, 10115756, -11829032, 3352736, 18551198, 3272828, -5190932, -4162409}, - }, - { - FieldElement{12501286, 4044383, -8612957, -13392385, -32430052, 5136599, -19230378, -3529697, 330070, -3659409}, - FieldElement{6384877, 2899513, 17807477, 7663917, -2358888, 12363165, 25366522, -8573892, -271295, 12071499}, - FieldElement{-8365515, -4042521, 25133448, -4517355, -6211027, 2265927, -32769618, 1936675, -5159697, 3829363}, - }, - { - FieldElement{28425966, -5835433, -577090, -4697198, -14217555, 6870930, 7921550, -6567787, 26333140, 14267664}, - FieldElement{-11067219, 11871231, 27385719, -10559544, -4585914, -11189312, 10004786, -8709488, -21761224, 8930324}, - FieldElement{-21197785, -16396035, 25654216, -1725397, 12282012, 11008919, 1541940, 4757911, -26491501, -16408940}, - }, - { - FieldElement{13537262, -7759490, -20604840, 10961927, -5922820, -13218065, -13156584, 6217254, -15943699, 13814990}, - FieldElement{-17422573, 15157790, 18705543, 29619, 24409717, -260476, 27361681, 9257833, -1956526, -1776914}, - FieldElement{-25045300, -10191966, 15366585, 15166509, -13105086, 8423556, -29171540, 12361135, -18685978, 4578290}, - }, - { - FieldElement{24579768, 3711570, 1342322, -11180126, -27005135, 14124956, -22544529, 14074919, 21964432, 8235257}, - FieldElement{-6528613, -2411497, 9442966, -5925588, 12025640, -1487420, -2981514, -1669206, 13006806, 2355433}, - FieldElement{-16304899, -13605259, -6632427, -5142349, 16974359, -10911083, 27202044, 1719366, 1141648, -12796236}, - }, - { - FieldElement{-12863944, -13219986, -8318266, -11018091, -6810145, -4843894, 13475066, -3133972, 32674895, 13715045}, - FieldElement{11423335, -5468059, 32344216, 8962751, 24989809, 9241752, -13265253, 16086212, -28740881, -15642093}, - FieldElement{-1409668, 12530728, -6368726, 10847387, 19531186, -14132160, -11709148, 7791794, -27245943, 4383347}, - }, - }, - { - { - FieldElement{-28970898, 5271447, -1266009, -9736989, -12455236, 16732599, -4862407, -4906449, 27193557, 6245191}, - FieldElement{-15193956, 5362278, -1783893, 2695834, 4960227, 12840725, 23061898, 3260492, 22510453, 8577507}, - FieldElement{-12632451, 11257346, -32692994, 13548177, -721004, 10879011, 31168030, 13952092, -29571492, -3635906}, - }, - { - FieldElement{3877321, -9572739, 32416692, 5405324, -11004407, -13656635, 3759769, 11935320, 5611860, 8164018}, - FieldElement{-16275802, 14667797, 15906460, 12155291, -22111149, -9039718, 32003002, -8832289, 5773085, -8422109}, - FieldElement{-23788118, -8254300, 1950875, 8937633, 18686727, 16459170, -905725, 12376320, 31632953, 190926}, - }, - { - FieldElement{-24593607, -16138885, -8423991, 13378746, 14162407, 6901328, -8288749, 4508564, -25341555, -3627528}, - FieldElement{8884438, -5884009, 6023974, 10104341, -6881569, -4941533, 18722941, -14786005, -1672488, 827625}, - FieldElement{-32720583, -16289296, -32503547, 7101210, 13354605, 2659080, -1800575, -14108036, -24878478, 1541286}, - }, - { - FieldElement{2901347, -1117687, 3880376, -10059388, -17620940, -3612781, -21802117, -3567481, 20456845, -1885033}, - FieldElement{27019610, 12299467, -13658288, -1603234, -12861660, -4861471, -19540150, -5016058, 29439641, 15138866}, - FieldElement{21536104, -6626420, -32447818, -10690208, -22408077, 5175814, -5420040, -16361163, 7779328, 109896}, - }, - { - FieldElement{30279744, 14648750, -8044871, 6425558, 13639621, -743509, 28698390, 12180118, 23177719, -554075}, - FieldElement{26572847, 3405927, -31701700, 12890905, -19265668, 5335866, -6493768, 2378492, 4439158, -13279347}, - FieldElement{-22716706, 3489070, -9225266, -332753, 18875722, -1140095, 14819434, -12731527, -17717757, -5461437}, - }, - { - FieldElement{-5056483, 16566551, 15953661, 3767752, -10436499, 15627060, -820954, 2177225, 8550082, -15114165}, - FieldElement{-18473302, 16596775, -381660, 15663611, 22860960, 15585581, -27844109, -3582739, -23260460, -8428588}, - FieldElement{-32480551, 15707275, -8205912, -5652081, 29464558, 2713815, -22725137, 15860482, -21902570, 1494193}, - }, - { - FieldElement{-19562091, -14087393, -25583872, -9299552, 13127842, 759709, 21923482, 16529112, 8742704, 12967017}, - FieldElement{-28464899, 1553205, 32536856, -10473729, -24691605, -406174, -8914625, -2933896, -29903758, 15553883}, - FieldElement{21877909, 3230008, 9881174, 10539357, -4797115, 2841332, 11543572, 14513274, 19375923, -12647961}, - }, - { - FieldElement{8832269, -14495485, 13253511, 5137575, 5037871, 4078777, 24880818, -6222716, 2862653, 9455043}, - FieldElement{29306751, 5123106, 20245049, -14149889, 9592566, 8447059, -2077124, -2990080, 15511449, 4789663}, - FieldElement{-20679756, 7004547, 8824831, -9434977, -4045704, -3750736, -5754762, 108893, 23513200, 16652362}, - }, - }, - { - { - FieldElement{-33256173, 4144782, -4476029, -6579123, 10770039, -7155542, -6650416, -12936300, -18319198, 10212860}, - FieldElement{2756081, 8598110, 7383731, -6859892, 22312759, -1105012, 21179801, 2600940, -9988298, -12506466}, - FieldElement{-24645692, 13317462, -30449259, -15653928, 21365574, -10869657, 11344424, 864440, -2499677, -16710063}, - }, - { - FieldElement{-26432803, 6148329, -17184412, -14474154, 18782929, -275997, -22561534, 211300, 2719757, 4940997}, - FieldElement{-1323882, 3911313, -6948744, 14759765, -30027150, 7851207, 21690126, 8518463, 26699843, 5276295}, - FieldElement{-13149873, -6429067, 9396249, 365013, 24703301, -10488939, 1321586, 149635, -15452774, 7159369}, - }, - { - FieldElement{9987780, -3404759, 17507962, 9505530, 9731535, -2165514, 22356009, 8312176, 22477218, -8403385}, - FieldElement{18155857, -16504990, 19744716, 9006923, 15154154, -10538976, 24256460, -4864995, -22548173, 9334109}, - FieldElement{2986088, -4911893, 10776628, -3473844, 10620590, -7083203, -21413845, 14253545, -22587149, 536906}, - }, - { - FieldElement{4377756, 8115836, 24567078, 15495314, 11625074, 13064599, 7390551, 10589625, 10838060, -15420424}, - FieldElement{-19342404, 867880, 9277171, -3218459, -14431572, -1986443, 19295826, -15796950, 6378260, 699185}, - FieldElement{7895026, 4057113, -7081772, -13077756, -17886831, -323126, -716039, 15693155, -5045064, -13373962}, - }, - { - FieldElement{-7737563, -5869402, -14566319, -7406919, 11385654, 13201616, 31730678, -10962840, -3918636, -9669325}, - FieldElement{10188286, -15770834, -7336361, 13427543, 22223443, 14896287, 30743455, 7116568, -21786507, 5427593}, - FieldElement{696102, 13206899, 27047647, -10632082, 15285305, -9853179, 10798490, -4578720, 19236243, 12477404}, - }, - { - FieldElement{-11229439, 11243796, -17054270, -8040865, -788228, -8167967, -3897669, 11180504, -23169516, 7733644}, - FieldElement{17800790, -14036179, -27000429, -11766671, 23887827, 3149671, 23466177, -10538171, 10322027, 15313801}, - FieldElement{26246234, 11968874, 32263343, -5468728, 6830755, -13323031, -15794704, -101982, -24449242, 10890804}, - }, - { - FieldElement{-31365647, 10271363, -12660625, -6267268, 16690207, -13062544, -14982212, 16484931, 25180797, -5334884}, - FieldElement{-586574, 10376444, -32586414, -11286356, 19801893, 10997610, 2276632, 9482883, 316878, 13820577}, - FieldElement{-9882808, -4510367, -2115506, 16457136, -11100081, 11674996, 30756178, -7515054, 30696930, -3712849}, - }, - { - FieldElement{32988917, -9603412, 12499366, 7910787, -10617257, -11931514, -7342816, -9985397, -32349517, 7392473}, - FieldElement{-8855661, 15927861, 9866406, -3649411, -2396914, -16655781, -30409476, -9134995, 25112947, -2926644}, - FieldElement{-2504044, -436966, 25621774, -5678772, 15085042, -5479877, -24884878, -13526194, 5537438, -13914319}, - }, - }, - { - { - FieldElement{-11225584, 2320285, -9584280, 10149187, -33444663, 5808648, -14876251, -1729667, 31234590, 6090599}, - FieldElement{-9633316, 116426, 26083934, 2897444, -6364437, -2688086, 609721, 15878753, -6970405, -9034768}, - FieldElement{-27757857, 247744, -15194774, -9002551, 23288161, -10011936, -23869595, 6503646, 20650474, 1804084}, - }, - { - FieldElement{-27589786, 15456424, 8972517, 8469608, 15640622, 4439847, 3121995, -10329713, 27842616, -202328}, - FieldElement{-15306973, 2839644, 22530074, 10026331, 4602058, 5048462, 28248656, 5031932, -11375082, 12714369}, - FieldElement{20807691, -7270825, 29286141, 11421711, -27876523, -13868230, -21227475, 1035546, -19733229, 12796920}, - }, - { - FieldElement{12076899, -14301286, -8785001, -11848922, -25012791, 16400684, -17591495, -12899438, 3480665, -15182815}, - FieldElement{-32361549, 5457597, 28548107, 7833186, 7303070, -11953545, -24363064, -15921875, -33374054, 2771025}, - FieldElement{-21389266, 421932, 26597266, 6860826, 22486084, -6737172, -17137485, -4210226, -24552282, 15673397}, - }, - { - FieldElement{-20184622, 2338216, 19788685, -9620956, -4001265, -8740893, -20271184, 4733254, 3727144, -12934448}, - FieldElement{6120119, 814863, -11794402, -622716, 6812205, -15747771, 2019594, 7975683, 31123697, -10958981}, - FieldElement{30069250, -11435332, 30434654, 2958439, 18399564, -976289, 12296869, 9204260, -16432438, 9648165}, - }, - { - FieldElement{32705432, -1550977, 30705658, 7451065, -11805606, 9631813, 3305266, 5248604, -26008332, -11377501}, - FieldElement{17219865, 2375039, -31570947, -5575615, -19459679, 9219903, 294711, 15298639, 2662509, -16297073}, - FieldElement{-1172927, -7558695, -4366770, -4287744, -21346413, -8434326, 32087529, -1222777, 32247248, -14389861}, - }, - { - FieldElement{14312628, 1221556, 17395390, -8700143, -4945741, -8684635, -28197744, -9637817, -16027623, -13378845}, - FieldElement{-1428825, -9678990, -9235681, 6549687, -7383069, -468664, 23046502, 9803137, 17597934, 2346211}, - FieldElement{18510800, 15337574, 26171504, 981392, -22241552, 7827556, -23491134, -11323352, 3059833, -11782870}, - }, - { - FieldElement{10141598, 6082907, 17829293, -1947643, 9830092, 13613136, -25556636, -5544586, -33502212, 3592096}, - FieldElement{33114168, -15889352, -26525686, -13343397, 33076705, 8716171, 1151462, 1521897, -982665, -6837803}, - FieldElement{-32939165, -4255815, 23947181, -324178, -33072974, -12305637, -16637686, 3891704, 26353178, 693168}, - }, - { - FieldElement{30374239, 1595580, -16884039, 13186931, 4600344, 406904, 9585294, -400668, 31375464, 14369965}, - FieldElement{-14370654, -7772529, 1510301, 6434173, -18784789, -6262728, 32732230, -13108839, 17901441, 16011505}, - FieldElement{18171223, -11934626, -12500402, 15197122, -11038147, -15230035, -19172240, -16046376, 8764035, 12309598}, - }, - }, - { - { - FieldElement{5975908, -5243188, -19459362, -9681747, -11541277, 14015782, -23665757, 1228319, 17544096, -10593782}, - FieldElement{5811932, -1715293, 3442887, -2269310, -18367348, -8359541, -18044043, -15410127, -5565381, 12348900}, - FieldElement{-31399660, 11407555, 25755363, 6891399, -3256938, 14872274, -24849353, 8141295, -10632534, -585479}, - }, - { - FieldElement{-12675304, 694026, -5076145, 13300344, 14015258, -14451394, -9698672, -11329050, 30944593, 1130208}, - FieldElement{8247766, -6710942, -26562381, -7709309, -14401939, -14648910, 4652152, 2488540, 23550156, -271232}, - FieldElement{17294316, -3788438, 7026748, 15626851, 22990044, 113481, 2267737, -5908146, -408818, -137719}, - }, - { - FieldElement{16091085, -16253926, 18599252, 7340678, 2137637, -1221657, -3364161, 14550936, 3260525, -7166271}, - FieldElement{-4910104, -13332887, 18550887, 10864893, -16459325, -7291596, -23028869, -13204905, -12748722, 2701326}, - FieldElement{-8574695, 16099415, 4629974, -16340524, -20786213, -6005432, -10018363, 9276971, 11329923, 1862132}, - }, - { - FieldElement{14763076, -15903608, -30918270, 3689867, 3511892, 10313526, -21951088, 12219231, -9037963, -940300}, - FieldElement{8894987, -3446094, 6150753, 3013931, 301220, 15693451, -31981216, -2909717, -15438168, 11595570}, - FieldElement{15214962, 3537601, -26238722, -14058872, 4418657, -15230761, 13947276, 10730794, -13489462, -4363670}, - }, - { - FieldElement{-2538306, 7682793, 32759013, 263109, -29984731, -7955452, -22332124, -10188635, 977108, 699994}, - FieldElement{-12466472, 4195084, -9211532, 550904, -15565337, 12917920, 19118110, -439841, -30534533, -14337913}, - FieldElement{31788461, -14507657, 4799989, 7372237, 8808585, -14747943, 9408237, -10051775, 12493932, -5409317}, - }, - { - FieldElement{-25680606, 5260744, -19235809, -6284470, -3695942, 16566087, 27218280, 2607121, 29375955, 6024730}, - FieldElement{842132, -2794693, -4763381, -8722815, 26332018, -12405641, 11831880, 6985184, -9940361, 2854096}, - FieldElement{-4847262, -7969331, 2516242, -5847713, 9695691, -7221186, 16512645, 960770, 12121869, 16648078}, - }, - { - FieldElement{-15218652, 14667096, -13336229, 2013717, 30598287, -464137, -31504922, -7882064, 20237806, 2838411}, - FieldElement{-19288047, 4453152, 15298546, -16178388, 22115043, -15972604, 12544294, -13470457, 1068881, -12499905}, - FieldElement{-9558883, -16518835, 33238498, 13506958, 30505848, -1114596, -8486907, -2630053, 12521378, 4845654}, - }, - { - FieldElement{-28198521, 10744108, -2958380, 10199664, 7759311, -13088600, 3409348, -873400, -6482306, -12885870}, - FieldElement{-23561822, 6230156, -20382013, 10655314, -24040585, -11621172, 10477734, -1240216, -3113227, 13974498}, - FieldElement{12966261, 15550616, -32038948, -1615346, 21025980, -629444, 5642325, 7188737, 18895762, 12629579}, - }, - }, - { - { - FieldElement{14741879, -14946887, 22177208, -11721237, 1279741, 8058600, 11758140, 789443, 32195181, 3895677}, - FieldElement{10758205, 15755439, -4509950, 9243698, -4879422, 6879879, -2204575, -3566119, -8982069, 4429647}, - FieldElement{-2453894, 15725973, -20436342, -10410672, -5803908, -11040220, -7135870, -11642895, 18047436, -15281743}, - }, - { - FieldElement{-25173001, -11307165, 29759956, 11776784, -22262383, -15820455, 10993114, -12850837, -17620701, -9408468}, - FieldElement{21987233, 700364, -24505048, 14972008, -7774265, -5718395, 32155026, 2581431, -29958985, 8773375}, - FieldElement{-25568350, 454463, -13211935, 16126715, 25240068, 8594567, 20656846, 12017935, -7874389, -13920155}, - }, - { - FieldElement{6028182, 6263078, -31011806, -11301710, -818919, 2461772, -31841174, -5468042, -1721788, -2776725}, - FieldElement{-12278994, 16624277, 987579, -5922598, 32908203, 1248608, 7719845, -4166698, 28408820, 6816612}, - FieldElement{-10358094, -8237829, 19549651, -12169222, 22082623, 16147817, 20613181, 13982702, -10339570, 5067943}, - }, - { - FieldElement{-30505967, -3821767, 12074681, 13582412, -19877972, 2443951, -19719286, 12746132, 5331210, -10105944}, - FieldElement{30528811, 3601899, -1957090, 4619785, -27361822, -15436388, 24180793, -12570394, 27679908, -1648928}, - FieldElement{9402404, -13957065, 32834043, 10838634, -26580150, -13237195, 26653274, -8685565, 22611444, -12715406}, - }, - { - FieldElement{22190590, 1118029, 22736441, 15130463, -30460692, -5991321, 19189625, -4648942, 4854859, 6622139}, - FieldElement{-8310738, -2953450, -8262579, -3388049, -10401731, -271929, 13424426, -3567227, 26404409, 13001963}, - FieldElement{-31241838, -15415700, -2994250, 8939346, 11562230, -12840670, -26064365, -11621720, -15405155, 11020693}, - }, - { - FieldElement{1866042, -7949489, -7898649, -10301010, 12483315, 13477547, 3175636, -12424163, 28761762, 1406734}, - FieldElement{-448555, -1777666, 13018551, 3194501, -9580420, -11161737, 24760585, -4347088, 25577411, -13378680}, - FieldElement{-24290378, 4759345, -690653, -1852816, 2066747, 10693769, -29595790, 9884936, -9368926, 4745410}, - }, - { - FieldElement{-9141284, 6049714, -19531061, -4341411, -31260798, 9944276, -15462008, -11311852, 10931924, -11931931}, - FieldElement{-16561513, 14112680, -8012645, 4817318, -8040464, -11414606, -22853429, 10856641, -20470770, 13434654}, - FieldElement{22759489, -10073434, -16766264, -1871422, 13637442, -10168091, 1765144, -12654326, 28445307, -5364710}, - }, - { - FieldElement{29875063, 12493613, 2795536, -3786330, 1710620, 15181182, -10195717, -8788675, 9074234, 1167180}, - FieldElement{-26205683, 11014233, -9842651, -2635485, -26908120, 7532294, -18716888, -9535498, 3843903, 9367684}, - FieldElement{-10969595, -6403711, 9591134, 9582310, 11349256, 108879, 16235123, 8601684, -139197, 4242895}, - }, - }, - { - { - FieldElement{22092954, -13191123, -2042793, -11968512, 32186753, -11517388, -6574341, 2470660, -27417366, 16625501}, - FieldElement{-11057722, 3042016, 13770083, -9257922, 584236, -544855, -7770857, 2602725, -27351616, 14247413}, - FieldElement{6314175, -10264892, -32772502, 15957557, -10157730, 168750, -8618807, 14290061, 27108877, -1180880}, - }, - { - FieldElement{-8586597, -7170966, 13241782, 10960156, -32991015, -13794596, 33547976, -11058889, -27148451, 981874}, - FieldElement{22833440, 9293594, -32649448, -13618667, -9136966, 14756819, -22928859, -13970780, -10479804, -16197962}, - FieldElement{-7768587, 3326786, -28111797, 10783824, 19178761, 14905060, 22680049, 13906969, -15933690, 3797899}, - }, - { - FieldElement{21721356, -4212746, -12206123, 9310182, -3882239, -13653110, 23740224, -2709232, 20491983, -8042152}, - FieldElement{9209270, -15135055, -13256557, -6167798, -731016, 15289673, 25947805, 15286587, 30997318, -6703063}, - FieldElement{7392032, 16618386, 23946583, -8039892, -13265164, -1533858, -14197445, -2321576, 17649998, -250080}, - }, - { - FieldElement{-9301088, -14193827, 30609526, -3049543, -25175069, -1283752, -15241566, -9525724, -2233253, 7662146}, - FieldElement{-17558673, 1763594, -33114336, 15908610, -30040870, -12174295, 7335080, -8472199, -3174674, 3440183}, - FieldElement{-19889700, -5977008, -24111293, -9688870, 10799743, -16571957, 40450, -4431835, 4862400, 1133}, - }, - { - FieldElement{-32856209, -7873957, -5422389, 14860950, -16319031, 7956142, 7258061, 311861, -30594991, -7379421}, - FieldElement{-3773428, -1565936, 28985340, 7499440, 24445838, 9325937, 29727763, 16527196, 18278453, 15405622}, - FieldElement{-4381906, 8508652, -19898366, -3674424, -5984453, 15149970, -13313598, 843523, -21875062, 13626197}, - }, - { - FieldElement{2281448, -13487055, -10915418, -2609910, 1879358, 16164207, -10783882, 3953792, 13340839, 15928663}, - FieldElement{31727126, -7179855, -18437503, -8283652, 2875793, -16390330, -25269894, -7014826, -23452306, 5964753}, - FieldElement{4100420, -5959452, -17179337, 6017714, -18705837, 12227141, -26684835, 11344144, 2538215, -7570755}, - }, - { - FieldElement{-9433605, 6123113, 11159803, -2156608, 30016280, 14966241, -20474983, 1485421, -629256, -15958862}, - FieldElement{-26804558, 4260919, 11851389, 9658551, -32017107, 16367492, -20205425, -13191288, 11659922, -11115118}, - FieldElement{26180396, 10015009, -30844224, -8581293, 5418197, 9480663, 2231568, -10170080, 33100372, -1306171}, - }, - { - FieldElement{15121113, -5201871, -10389905, 15427821, -27509937, -15992507, 21670947, 4486675, -5931810, -14466380}, - FieldElement{16166486, -9483733, -11104130, 6023908, -31926798, -1364923, 2340060, -16254968, -10735770, -10039824}, - FieldElement{28042865, -3557089, -12126526, 12259706, -3717498, -6945899, 6766453, -8689599, 18036436, 5803270}, - }, - }, - { - { - FieldElement{-817581, 6763912, 11803561, 1585585, 10958447, -2671165, 23855391, 4598332, -6159431, -14117438}, - FieldElement{-31031306, -14256194, 17332029, -2383520, 31312682, -5967183, 696309, 50292, -20095739, 11763584}, - FieldElement{-594563, -2514283, -32234153, 12643980, 12650761, 14811489, 665117, -12613632, -19773211, -10713562}, - }, - { - FieldElement{30464590, -11262872, -4127476, -12734478, 19835327, -7105613, -24396175, 2075773, -17020157, 992471}, - FieldElement{18357185, -6994433, 7766382, 16342475, -29324918, 411174, 14578841, 8080033, -11574335, -10601610}, - FieldElement{19598397, 10334610, 12555054, 2555664, 18821899, -10339780, 21873263, 16014234, 26224780, 16452269}, - }, - { - FieldElement{-30223925, 5145196, 5944548, 16385966, 3976735, 2009897, -11377804, -7618186, -20533829, 3698650}, - FieldElement{14187449, 3448569, -10636236, -10810935, -22663880, -3433596, 7268410, -10890444, 27394301, 12015369}, - FieldElement{19695761, 16087646, 28032085, 12999827, 6817792, 11427614, 20244189, -1312777, -13259127, -3402461}, - }, - { - FieldElement{30860103, 12735208, -1888245, -4699734, -16974906, 2256940, -8166013, 12298312, -8550524, -10393462}, - FieldElement{-5719826, -11245325, -1910649, 15569035, 26642876, -7587760, -5789354, -15118654, -4976164, 12651793}, - FieldElement{-2848395, 9953421, 11531313, -5282879, 26895123, -12697089, -13118820, -16517902, 9768698, -2533218}, - }, - { - FieldElement{-24719459, 1894651, -287698, -4704085, 15348719, -8156530, 32767513, 12765450, 4940095, 10678226}, - FieldElement{18860224, 15980149, -18987240, -1562570, -26233012, -11071856, -7843882, 13944024, -24372348, 16582019}, - FieldElement{-15504260, 4970268, -29893044, 4175593, -20993212, -2199756, -11704054, 15444560, -11003761, 7989037}, - }, - { - FieldElement{31490452, 5568061, -2412803, 2182383, -32336847, 4531686, -32078269, 6200206, -19686113, -14800171}, - FieldElement{-17308668, -15879940, -31522777, -2831, -32887382, 16375549, 8680158, -16371713, 28550068, -6857132}, - FieldElement{-28126887, -5688091, 16837845, -1820458, -6850681, 12700016, -30039981, 4364038, 1155602, 5988841}, - }, - { - FieldElement{21890435, -13272907, -12624011, 12154349, -7831873, 15300496, 23148983, -4470481, 24618407, 8283181}, - FieldElement{-33136107, -10512751, 9975416, 6841041, -31559793, 16356536, 3070187, -7025928, 1466169, 10740210}, - FieldElement{-1509399, -15488185, -13503385, -10655916, 32799044, 909394, -13938903, -5779719, -32164649, -15327040}, - }, - { - FieldElement{3960823, -14267803, -28026090, -15918051, -19404858, 13146868, 15567327, 951507, -3260321, -573935}, - FieldElement{24740841, 5052253, -30094131, 8961361, 25877428, 6165135, -24368180, 14397372, -7380369, -6144105}, - FieldElement{-28888365, 3510803, -28103278, -1158478, -11238128, -10631454, -15441463, -14453128, -1625486, -6494814}, - }, - }, - { - { - FieldElement{793299, -9230478, 8836302, -6235707, -27360908, -2369593, 33152843, -4885251, -9906200, -621852}, - FieldElement{5666233, 525582, 20782575, -8038419, -24538499, 14657740, 16099374, 1468826, -6171428, -15186581}, - FieldElement{-4859255, -3779343, -2917758, -6748019, 7778750, 11688288, -30404353, -9871238, -1558923, -9863646}, - }, - { - FieldElement{10896332, -7719704, 824275, 472601, -19460308, 3009587, 25248958, 14783338, -30581476, -15757844}, - FieldElement{10566929, 12612572, -31944212, 11118703, -12633376, 12362879, 21752402, 8822496, 24003793, 14264025}, - FieldElement{27713862, -7355973, -11008240, 9227530, 27050101, 2504721, 23886875, -13117525, 13958495, -5732453}, - }, - { - FieldElement{-23481610, 4867226, -27247128, 3900521, 29838369, -8212291, -31889399, -10041781, 7340521, -15410068}, - FieldElement{4646514, -8011124, -22766023, -11532654, 23184553, 8566613, 31366726, -1381061, -15066784, -10375192}, - FieldElement{-17270517, 12723032, -16993061, 14878794, 21619651, -6197576, 27584817, 3093888, -8843694, 3849921}, - }, - { - FieldElement{-9064912, 2103172, 25561640, -15125738, -5239824, 9582958, 32477045, -9017955, 5002294, -15550259}, - FieldElement{-12057553, -11177906, 21115585, -13365155, 8808712, -12030708, 16489530, 13378448, -25845716, 12741426}, - FieldElement{-5946367, 10645103, -30911586, 15390284, -3286982, -7118677, 24306472, 15852464, 28834118, -7646072}, - }, - { - FieldElement{-17335748, -9107057, -24531279, 9434953, -8472084, -583362, -13090771, 455841, 20461858, 5491305}, - FieldElement{13669248, -16095482, -12481974, -10203039, -14569770, -11893198, -24995986, 11293807, -28588204, -9421832}, - FieldElement{28497928, 6272777, -33022994, 14470570, 8906179, -1225630, 18504674, -14165166, 29867745, -8795943}, - }, - { - FieldElement{-16207023, 13517196, -27799630, -13697798, 24009064, -6373891, -6367600, -13175392, 22853429, -4012011}, - FieldElement{24191378, 16712145, -13931797, 15217831, 14542237, 1646131, 18603514, -11037887, 12876623, -2112447}, - FieldElement{17902668, 4518229, -411702, -2829247, 26878217, 5258055, -12860753, 608397, 16031844, 3723494}, - }, - { - FieldElement{-28632773, 12763728, -20446446, 7577504, 33001348, -13017745, 17558842, -7872890, 23896954, -4314245}, - FieldElement{-20005381, -12011952, 31520464, 605201, 2543521, 5991821, -2945064, 7229064, -9919646, -8826859}, - FieldElement{28816045, 298879, -28165016, -15920938, 19000928, -1665890, -12680833, -2949325, -18051778, -2082915}, - }, - { - FieldElement{16000882, -344896, 3493092, -11447198, -29504595, -13159789, 12577740, 16041268, -19715240, 7847707}, - FieldElement{10151868, 10572098, 27312476, 7922682, 14825339, 4723128, -32855931, -6519018, -10020567, 3852848}, - FieldElement{-11430470, 15697596, -21121557, -4420647, 5386314, 15063598, 16514493, -15932110, 29330899, -15076224}, - }, - }, - { - { - FieldElement{-25499735, -4378794, -15222908, -6901211, 16615731, 2051784, 3303702, 15490, -27548796, 12314391}, - FieldElement{15683520, -6003043, 18109120, -9980648, 15337968, -5997823, -16717435, 15921866, 16103996, -3731215}, - FieldElement{-23169824, -10781249, 13588192, -1628807, -3798557, -1074929, -19273607, 5402699, -29815713, -9841101}, - }, - { - FieldElement{23190676, 2384583, -32714340, 3462154, -29903655, -1529132, -11266856, 8911517, -25205859, 2739713}, - FieldElement{21374101, -3554250, -33524649, 9874411, 15377179, 11831242, -33529904, 6134907, 4931255, 11987849}, - FieldElement{-7732, -2978858, -16223486, 7277597, 105524, -322051, -31480539, 13861388, -30076310, 10117930}, - }, - { - FieldElement{-29501170, -10744872, -26163768, 13051539, -25625564, 5089643, -6325503, 6704079, 12890019, 15728940}, - FieldElement{-21972360, -11771379, -951059, -4418840, 14704840, 2695116, 903376, -10428139, 12885167, 8311031}, - FieldElement{-17516482, 5352194, 10384213, -13811658, 7506451, 13453191, 26423267, 4384730, 1888765, -5435404}, - }, - { - FieldElement{-25817338, -3107312, -13494599, -3182506, 30896459, -13921729, -32251644, -12707869, -19464434, -3340243}, - FieldElement{-23607977, -2665774, -526091, 4651136, 5765089, 4618330, 6092245, 14845197, 17151279, -9854116}, - FieldElement{-24830458, -12733720, -15165978, 10367250, -29530908, -265356, 22825805, -7087279, -16866484, 16176525}, - }, - { - FieldElement{-23583256, 6564961, 20063689, 3798228, -4740178, 7359225, 2006182, -10363426, -28746253, -10197509}, - FieldElement{-10626600, -4486402, -13320562, -5125317, 3432136, -6393229, 23632037, -1940610, 32808310, 1099883}, - FieldElement{15030977, 5768825, -27451236, -2887299, -6427378, -15361371, -15277896, -6809350, 2051441, -15225865}, - }, - { - FieldElement{-3362323, -7239372, 7517890, 9824992, 23555850, 295369, 5148398, -14154188, -22686354, 16633660}, - FieldElement{4577086, -16752288, 13249841, -15304328, 19958763, -14537274, 18559670, -10759549, 8402478, -9864273}, - FieldElement{-28406330, -1051581, -26790155, -907698, -17212414, -11030789, 9453451, -14980072, 17983010, 9967138}, - }, - { - FieldElement{-25762494, 6524722, 26585488, 9969270, 24709298, 1220360, -1677990, 7806337, 17507396, 3651560}, - FieldElement{-10420457, -4118111, 14584639, 15971087, -15768321, 8861010, 26556809, -5574557, -18553322, -11357135}, - FieldElement{2839101, 14284142, 4029895, 3472686, 14402957, 12689363, -26642121, 8459447, -5605463, -7621941}, - }, - { - FieldElement{-4839289, -3535444, 9744961, 2871048, 25113978, 3187018, -25110813, -849066, 17258084, -7977739}, - FieldElement{18164541, -10595176, -17154882, -1542417, 19237078, -9745295, 23357533, -15217008, 26908270, 12150756}, - FieldElement{-30264870, -7647865, 5112249, -7036672, -1499807, -6974257, 43168, -5537701, -32302074, 16215819}, - }, - }, - { - { - FieldElement{-6898905, 9824394, -12304779, -4401089, -31397141, -6276835, 32574489, 12532905, -7503072, -8675347}, - FieldElement{-27343522, -16515468, -27151524, -10722951, 946346, 16291093, 254968, 7168080, 21676107, -1943028}, - FieldElement{21260961, -8424752, -16831886, -11920822, -23677961, 3968121, -3651949, -6215466, -3556191, -7913075}, - }, - { - FieldElement{16544754, 13250366, -16804428, 15546242, -4583003, 12757258, -2462308, -8680336, -18907032, -9662799}, - FieldElement{-2415239, -15577728, 18312303, 4964443, -15272530, -12653564, 26820651, 16690659, 25459437, -4564609}, - FieldElement{-25144690, 11425020, 28423002, -11020557, -6144921, -15826224, 9142795, -2391602, -6432418, -1644817}, - }, - { - FieldElement{-23104652, 6253476, 16964147, -3768872, -25113972, -12296437, -27457225, -16344658, 6335692, 7249989}, - FieldElement{-30333227, 13979675, 7503222, -12368314, -11956721, -4621693, -30272269, 2682242, 25993170, -12478523}, - FieldElement{4364628, 5930691, 32304656, -10044554, -8054781, 15091131, 22857016, -10598955, 31820368, 15075278}, - }, - { - FieldElement{31879134, -8918693, 17258761, 90626, -8041836, -4917709, 24162788, -9650886, -17970238, 12833045}, - FieldElement{19073683, 14851414, -24403169, -11860168, 7625278, 11091125, -19619190, 2074449, -9413939, 14905377}, - FieldElement{24483667, -11935567, -2518866, -11547418, -1553130, 15355506, -25282080, 9253129, 27628530, -7555480}, - }, - { - FieldElement{17597607, 8340603, 19355617, 552187, 26198470, -3176583, 4593324, -9157582, -14110875, 15297016}, - FieldElement{510886, 14337390, -31785257, 16638632, 6328095, 2713355, -20217417, -11864220, 8683221, 2921426}, - FieldElement{18606791, 11874196, 27155355, -5281482, -24031742, 6265446, -25178240, -1278924, 4674690, 13890525}, - }, - { - FieldElement{13609624, 13069022, -27372361, -13055908, 24360586, 9592974, 14977157, 9835105, 4389687, 288396}, - FieldElement{9922506, -519394, 13613107, 5883594, -18758345, -434263, -12304062, 8317628, 23388070, 16052080}, - FieldElement{12720016, 11937594, -31970060, -5028689, 26900120, 8561328, -20155687, -11632979, -14754271, -10812892}, - }, - { - FieldElement{15961858, 14150409, 26716931, -665832, -22794328, 13603569, 11829573, 7467844, -28822128, 929275}, - FieldElement{11038231, -11582396, -27310482, -7316562, -10498527, -16307831, -23479533, -9371869, -21393143, 2465074}, - FieldElement{20017163, -4323226, 27915242, 1529148, 12396362, 15675764, 13817261, -9658066, 2463391, -4622140}, - }, - { - FieldElement{-16358878, -12663911, -12065183, 4996454, -1256422, 1073572, 9583558, 12851107, 4003896, 12673717}, - FieldElement{-1731589, -15155870, -3262930, 16143082, 19294135, 13385325, 14741514, -9103726, 7903886, 2348101}, - FieldElement{24536016, -16515207, 12715592, -3862155, 1511293, 10047386, -3842346, -7129159, -28377538, 10048127}, - }, - }, - { - { - FieldElement{-12622226, -6204820, 30718825, 2591312, -10617028, 12192840, 18873298, -7297090, -32297756, 15221632}, - FieldElement{-26478122, -11103864, 11546244, -1852483, 9180880, 7656409, -21343950, 2095755, 29769758, 6593415}, - FieldElement{-31994208, -2907461, 4176912, 3264766, 12538965, -868111, 26312345, -6118678, 30958054, 8292160}, - }, - { - FieldElement{31429822, -13959116, 29173532, 15632448, 12174511, -2760094, 32808831, 3977186, 26143136, -3148876}, - FieldElement{22648901, 1402143, -22799984, 13746059, 7936347, 365344, -8668633, -1674433, -3758243, -2304625}, - FieldElement{-15491917, 8012313, -2514730, -12702462, -23965846, -10254029, -1612713, -1535569, -16664475, 8194478}, - }, - { - FieldElement{27338066, -7507420, -7414224, 10140405, -19026427, -6589889, 27277191, 8855376, 28572286, 3005164}, - FieldElement{26287124, 4821776, 25476601, -4145903, -3764513, -15788984, -18008582, 1182479, -26094821, -13079595}, - FieldElement{-7171154, 3178080, 23970071, 6201893, -17195577, -4489192, -21876275, -13982627, 32208683, -1198248}, - }, - { - FieldElement{-16657702, 2817643, -10286362, 14811298, 6024667, 13349505, -27315504, -10497842, -27672585, -11539858}, - FieldElement{15941029, -9405932, -21367050, 8062055, 31876073, -238629, -15278393, -1444429, 15397331, -4130193}, - FieldElement{8934485, -13485467, -23286397, -13423241, -32446090, 14047986, 31170398, -1441021, -27505566, 15087184}, - }, - { - FieldElement{-18357243, -2156491, 24524913, -16677868, 15520427, -6360776, -15502406, 11461896, 16788528, -5868942}, - FieldElement{-1947386, 16013773, 21750665, 3714552, -17401782, -16055433, -3770287, -10323320, 31322514, -11615635}, - FieldElement{21426655, -5650218, -13648287, -5347537, -28812189, -4920970, -18275391, -14621414, 13040862, -12112948}, - }, - { - FieldElement{11293895, 12478086, -27136401, 15083750, -29307421, 14748872, 14555558, -13417103, 1613711, 4896935}, - FieldElement{-25894883, 15323294, -8489791, -8057900, 25967126, -13425460, 2825960, -4897045, -23971776, -11267415}, - FieldElement{-15924766, -5229880, -17443532, 6410664, 3622847, 10243618, 20615400, 12405433, -23753030, -8436416}, - }, - { - FieldElement{-7091295, 12556208, -20191352, 9025187, -17072479, 4333801, 4378436, 2432030, 23097949, -566018}, - FieldElement{4565804, -16025654, 20084412, -7842817, 1724999, 189254, 24767264, 10103221, -18512313, 2424778}, - FieldElement{366633, -11976806, 8173090, -6890119, 30788634, 5745705, -7168678, 1344109, -3642553, 12412659}, - }, - { - FieldElement{-24001791, 7690286, 14929416, -168257, -32210835, -13412986, 24162697, -15326504, -3141501, 11179385}, - FieldElement{18289522, -14724954, 8056945, 16430056, -21729724, 7842514, -6001441, -1486897, -18684645, -11443503}, - FieldElement{476239, 6601091, -6152790, -9723375, 17503545, -4863900, 27672959, 13403813, 11052904, 5219329}, - }, - }, - { - { - FieldElement{20678546, -8375738, -32671898, 8849123, -5009758, 14574752, 31186971, -3973730, 9014762, -8579056}, - FieldElement{-13644050, -10350239, -15962508, 5075808, -1514661, -11534600, -33102500, 9160280, 8473550, -3256838}, - FieldElement{24900749, 14435722, 17209120, -15292541, -22592275, 9878983, -7689309, -16335821, -24568481, 11788948}, - }, - { - FieldElement{-3118155, -11395194, -13802089, 14797441, 9652448, -6845904, -20037437, 10410733, -24568470, -1458691}, - FieldElement{-15659161, 16736706, -22467150, 10215878, -9097177, 7563911, 11871841, -12505194, -18513325, 8464118}, - FieldElement{-23400612, 8348507, -14585951, -861714, -3950205, -6373419, 14325289, 8628612, 33313881, -8370517}, - }, - { - FieldElement{-20186973, -4967935, 22367356, 5271547, -1097117, -4788838, -24805667, -10236854, -8940735, -5818269}, - FieldElement{-6948785, -1795212, -32625683, -16021179, 32635414, -7374245, 15989197, -12838188, 28358192, -4253904}, - FieldElement{-23561781, -2799059, -32351682, -1661963, -9147719, 10429267, -16637684, 4072016, -5351664, 5596589}, - }, - { - FieldElement{-28236598, -3390048, 12312896, 6213178, 3117142, 16078565, 29266239, 2557221, 1768301, 15373193}, - FieldElement{-7243358, -3246960, -4593467, -7553353, -127927, -912245, -1090902, -4504991, -24660491, 3442910}, - FieldElement{-30210571, 5124043, 14181784, 8197961, 18964734, -11939093, 22597931, 7176455, -18585478, 13365930}, - }, - { - FieldElement{-7877390, -1499958, 8324673, 4690079, 6261860, 890446, 24538107, -8570186, -9689599, -3031667}, - FieldElement{25008904, -10771599, -4305031, -9638010, 16265036, 15721635, 683793, -11823784, 15723479, -15163481}, - FieldElement{-9660625, 12374379, -27006999, -7026148, -7724114, -12314514, 11879682, 5400171, 519526, -1235876}, - }, - { - FieldElement{22258397, -16332233, -7869817, 14613016, -22520255, -2950923, -20353881, 7315967, 16648397, 7605640}, - FieldElement{-8081308, -8464597, -8223311, 9719710, 19259459, -15348212, 23994942, -5281555, -9468848, 4763278}, - FieldElement{-21699244, 9220969, -15730624, 1084137, -25476107, -2852390, 31088447, -7764523, -11356529, 728112}, - }, - { - FieldElement{26047220, -11751471, -6900323, -16521798, 24092068, 9158119, -4273545, -12555558, -29365436, -5498272}, - FieldElement{17510331, -322857, 5854289, 8403524, 17133918, -3112612, -28111007, 12327945, 10750447, 10014012}, - FieldElement{-10312768, 3936952, 9156313, -8897683, 16498692, -994647, -27481051, -666732, 3424691, 7540221}, - }, - { - FieldElement{30322361, -6964110, 11361005, -4143317, 7433304, 4989748, -7071422, -16317219, -9244265, 15258046}, - FieldElement{13054562, -2779497, 19155474, 469045, -12482797, 4566042, 5631406, 2711395, 1062915, -5136345}, - FieldElement{-19240248, -11254599, -29509029, -7499965, -5835763, 13005411, -6066489, 12194497, 32960380, 1459310}, - }, - }, - { - { - FieldElement{19852034, 7027924, 23669353, 10020366, 8586503, -6657907, 394197, -6101885, 18638003, -11174937}, - FieldElement{31395534, 15098109, 26581030, 8030562, -16527914, -5007134, 9012486, -7584354, -6643087, -5442636}, - FieldElement{-9192165, -2347377, -1997099, 4529534, 25766844, 607986, -13222, 9677543, -32294889, -6456008}, - }, - { - FieldElement{-2444496, -149937, 29348902, 8186665, 1873760, 12489863, -30934579, -7839692, -7852844, -8138429}, - FieldElement{-15236356, -15433509, 7766470, 746860, 26346930, -10221762, -27333451, 10754588, -9431476, 5203576}, - FieldElement{31834314, 14135496, -770007, 5159118, 20917671, -16768096, -7467973, -7337524, 31809243, 7347066}, - }, - { - FieldElement{-9606723, -11874240, 20414459, 13033986, 13716524, -11691881, 19797970, -12211255, 15192876, -2087490}, - FieldElement{-12663563, -2181719, 1168162, -3804809, 26747877, -14138091, 10609330, 12694420, 33473243, -13382104}, - FieldElement{33184999, 11180355, 15832085, -11385430, -1633671, 225884, 15089336, -11023903, -6135662, 14480053}, - }, - { - FieldElement{31308717, -5619998, 31030840, -1897099, 15674547, -6582883, 5496208, 13685227, 27595050, 8737275}, - FieldElement{-20318852, -15150239, 10933843, -16178022, 8335352, -7546022, -31008351, -12610604, 26498114, 66511}, - FieldElement{22644454, -8761729, -16671776, 4884562, -3105614, -13559366, 30540766, -4286747, -13327787, -7515095}, - }, - { - FieldElement{-28017847, 9834845, 18617207, -2681312, -3401956, -13307506, 8205540, 13585437, -17127465, 15115439}, - FieldElement{23711543, -672915, 31206561, -8362711, 6164647, -9709987, -33535882, -1426096, 8236921, 16492939}, - FieldElement{-23910559, -13515526, -26299483, -4503841, 25005590, -7687270, 19574902, 10071562, 6708380, -6222424}, - }, - { - FieldElement{2101391, -4930054, 19702731, 2367575, -15427167, 1047675, 5301017, 9328700, 29955601, -11678310}, - FieldElement{3096359, 9271816, -21620864, -15521844, -14847996, -7592937, -25892142, -12635595, -9917575, 6216608}, - FieldElement{-32615849, 338663, -25195611, 2510422, -29213566, -13820213, 24822830, -6146567, -26767480, 7525079}, - }, - { - FieldElement{-23066649, -13985623, 16133487, -7896178, -3389565, 778788, -910336, -2782495, -19386633, 11994101}, - FieldElement{21691500, -13624626, -641331, -14367021, 3285881, -3483596, -25064666, 9718258, -7477437, 13381418}, - FieldElement{18445390, -4202236, 14979846, 11622458, -1727110, -3582980, 23111648, -6375247, 28535282, 15779576}, - }, - { - FieldElement{30098053, 3089662, -9234387, 16662135, -21306940, 11308411, -14068454, 12021730, 9955285, -16303356}, - FieldElement{9734894, -14576830, -7473633, -9138735, 2060392, 11313496, -18426029, 9924399, 20194861, 13380996}, - FieldElement{-26378102, -7965207, -22167821, 15789297, -18055342, -6168792, -1984914, 15707771, 26342023, 10146099}, - }, - }, - { - { - FieldElement{-26016874, -219943, 21339191, -41388, 19745256, -2878700, -29637280, 2227040, 21612326, -545728}, - FieldElement{-13077387, 1184228, 23562814, -5970442, -20351244, -6348714, 25764461, 12243797, -20856566, 11649658}, - FieldElement{-10031494, 11262626, 27384172, 2271902, 26947504, -15997771, 39944, 6114064, 33514190, 2333242}, - }, - { - FieldElement{-21433588, -12421821, 8119782, 7219913, -21830522, -9016134, -6679750, -12670638, 24350578, -13450001}, - FieldElement{-4116307, -11271533, -23886186, 4843615, -30088339, 690623, -31536088, -10406836, 8317860, 12352766}, - FieldElement{18200138, -14475911, -33087759, -2696619, -23702521, -9102511, -23552096, -2287550, 20712163, 6719373}, - }, - { - FieldElement{26656208, 6075253, -7858556, 1886072, -28344043, 4262326, 11117530, -3763210, 26224235, -3297458}, - FieldElement{-17168938, -14854097, -3395676, -16369877, -19954045, 14050420, 21728352, 9493610, 18620611, -16428628}, - FieldElement{-13323321, 13325349, 11432106, 5964811, 18609221, 6062965, -5269471, -9725556, -30701573, -16479657}, - }, - { - FieldElement{-23860538, -11233159, 26961357, 1640861, -32413112, -16737940, 12248509, -5240639, 13735342, 1934062}, - FieldElement{25089769, 6742589, 17081145, -13406266, 21909293, -16067981, -15136294, -3765346, -21277997, 5473616}, - FieldElement{31883677, -7961101, 1083432, -11572403, 22828471, 13290673, -7125085, 12469656, 29111212, -5451014}, - }, - { - FieldElement{24244947, -15050407, -26262976, 2791540, -14997599, 16666678, 24367466, 6388839, -10295587, 452383}, - FieldElement{-25640782, -3417841, 5217916, 16224624, 19987036, -4082269, -24236251, -5915248, 15766062, 8407814}, - FieldElement{-20406999, 13990231, 15495425, 16395525, 5377168, 15166495, -8917023, -4388953, -8067909, 2276718}, - }, - { - FieldElement{30157918, 12924066, -17712050, 9245753, 19895028, 3368142, -23827587, 5096219, 22740376, -7303417}, - FieldElement{2041139, -14256350, 7783687, 13876377, -25946985, -13352459, 24051124, 13742383, -15637599, 13295222}, - FieldElement{33338237, -8505733, 12532113, 7977527, 9106186, -1715251, -17720195, -4612972, -4451357, -14669444}, - }, - { - FieldElement{-20045281, 5454097, -14346548, 6447146, 28862071, 1883651, -2469266, -4141880, 7770569, 9620597}, - FieldElement{23208068, 7979712, 33071466, 8149229, 1758231, -10834995, 30945528, -1694323, -33502340, -14767970}, - FieldElement{1439958, -16270480, -1079989, -793782, 4625402, 10647766, -5043801, 1220118, 30494170, -11440799}, - }, - { - FieldElement{-5037580, -13028295, -2970559, -3061767, 15640974, -6701666, -26739026, 926050, -1684339, -13333647}, - FieldElement{13908495, -3549272, 30919928, -6273825, -21521863, 7989039, 9021034, 9078865, 3353509, 4033511}, - FieldElement{-29663431, -15113610, 32259991, -344482, 24295849, -12912123, 23161163, 8839127, 27485041, 7356032}, - }, - }, - { - { - FieldElement{9661027, 705443, 11980065, -5370154, -1628543, 14661173, -6346142, 2625015, 28431036, -16771834}, - FieldElement{-23839233, -8311415, -25945511, 7480958, -17681669, -8354183, -22545972, 14150565, 15970762, 4099461}, - FieldElement{29262576, 16756590, 26350592, -8793563, 8529671, -11208050, 13617293, -9937143, 11465739, 8317062}, - }, - { - FieldElement{-25493081, -6962928, 32500200, -9419051, -23038724, -2302222, 14898637, 3848455, 20969334, -5157516}, - FieldElement{-20384450, -14347713, -18336405, 13884722, -33039454, 2842114, -21610826, -3649888, 11177095, 14989547}, - FieldElement{-24496721, -11716016, 16959896, 2278463, 12066309, 10137771, 13515641, 2581286, -28487508, 9930240}, - }, - { - FieldElement{-17751622, -2097826, 16544300, -13009300, -15914807, -14949081, 18345767, -13403753, 16291481, -5314038}, - FieldElement{-33229194, 2553288, 32678213, 9875984, 8534129, 6889387, -9676774, 6957617, 4368891, 9788741}, - FieldElement{16660756, 7281060, -10830758, 12911820, 20108584, -8101676, -21722536, -8613148, 16250552, -11111103}, - }, - { - FieldElement{-19765507, 2390526, -16551031, 14161980, 1905286, 6414907, 4689584, 10604807, -30190403, 4782747}, - FieldElement{-1354539, 14736941, -7367442, -13292886, 7710542, -14155590, -9981571, 4383045, 22546403, 437323}, - FieldElement{31665577, -12180464, -16186830, 1491339, -18368625, 3294682, 27343084, 2786261, -30633590, -14097016}, - }, - { - FieldElement{-14467279, -683715, -33374107, 7448552, 19294360, 14334329, -19690631, 2355319, -19284671, -6114373}, - FieldElement{15121312, -15796162, 6377020, -6031361, -10798111, -12957845, 18952177, 15496498, -29380133, 11754228}, - FieldElement{-2637277, -13483075, 8488727, -14303896, 12728761, -1622493, 7141596, 11724556, 22761615, -10134141}, - }, - { - FieldElement{16918416, 11729663, -18083579, 3022987, -31015732, -13339659, -28741185, -12227393, 32851222, 11717399}, - FieldElement{11166634, 7338049, -6722523, 4531520, -29468672, -7302055, 31474879, 3483633, -1193175, -4030831}, - FieldElement{-185635, 9921305, 31456609, -13536438, -12013818, 13348923, 33142652, 6546660, -19985279, -3948376}, - }, - { - FieldElement{-32460596, 11266712, -11197107, -7899103, 31703694, 3855903, -8537131, -12833048, -30772034, -15486313}, - FieldElement{-18006477, 12709068, 3991746, -6479188, -21491523, -10550425, -31135347, -16049879, 10928917, 3011958}, - FieldElement{-6957757, -15594337, 31696059, 334240, 29576716, 14796075, -30831056, -12805180, 18008031, 10258577}, - }, - { - FieldElement{-22448644, 15655569, 7018479, -4410003, -30314266, -1201591, -1853465, 1367120, 25127874, 6671743}, - FieldElement{29701166, -14373934, -10878120, 9279288, -17568, 13127210, 21382910, 11042292, 25838796, 4642684}, - FieldElement{-20430234, 14955537, -24126347, 8124619, -5369288, -5990470, 30468147, -13900640, 18423289, 4177476}, - }, - }, -} diff --git a/vendor/golang.org/x/crypto/ed25519/internal/edwards25519/edwards25519.go b/vendor/golang.org/x/crypto/ed25519/internal/edwards25519/edwards25519.go deleted file mode 100644 index 5f8b994..0000000 --- a/vendor/golang.org/x/crypto/ed25519/internal/edwards25519/edwards25519.go +++ /dev/null @@ -1,1771 +0,0 @@ -// Copyright 2016 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 edwards25519 - -// This code is a port of the public domain, “ref10” implementation of ed25519 -// from SUPERCOP. - -// FieldElement represents an element of the field GF(2^255 - 19). An element -// t, entries t[0]...t[9], represents the integer t[0]+2^26 t[1]+2^51 t[2]+2^77 -// t[3]+2^102 t[4]+...+2^230 t[9]. Bounds on each t[i] vary depending on -// context. -type FieldElement [10]int32 - -var zero FieldElement - -func FeZero(fe *FieldElement) { - copy(fe[:], zero[:]) -} - -func FeOne(fe *FieldElement) { - FeZero(fe) - fe[0] = 1 -} - -func FeAdd(dst, a, b *FieldElement) { - dst[0] = a[0] + b[0] - dst[1] = a[1] + b[1] - dst[2] = a[2] + b[2] - dst[3] = a[3] + b[3] - dst[4] = a[4] + b[4] - dst[5] = a[5] + b[5] - dst[6] = a[6] + b[6] - dst[7] = a[7] + b[7] - dst[8] = a[8] + b[8] - dst[9] = a[9] + b[9] -} - -func FeSub(dst, a, b *FieldElement) { - dst[0] = a[0] - b[0] - dst[1] = a[1] - b[1] - dst[2] = a[2] - b[2] - dst[3] = a[3] - b[3] - dst[4] = a[4] - b[4] - dst[5] = a[5] - b[5] - dst[6] = a[6] - b[6] - dst[7] = a[7] - b[7] - dst[8] = a[8] - b[8] - dst[9] = a[9] - b[9] -} - -func FeCopy(dst, src *FieldElement) { - copy(dst[:], src[:]) -} - -// Replace (f,g) with (g,g) if b == 1; -// replace (f,g) with (f,g) if b == 0. -// -// Preconditions: b in {0,1}. -func FeCMove(f, g *FieldElement, b int32) { - b = -b - f[0] ^= b & (f[0] ^ g[0]) - f[1] ^= b & (f[1] ^ g[1]) - f[2] ^= b & (f[2] ^ g[2]) - f[3] ^= b & (f[3] ^ g[3]) - f[4] ^= b & (f[4] ^ g[4]) - f[5] ^= b & (f[5] ^ g[5]) - f[6] ^= b & (f[6] ^ g[6]) - f[7] ^= b & (f[7] ^ g[7]) - f[8] ^= b & (f[8] ^ g[8]) - f[9] ^= b & (f[9] ^ g[9]) -} - -func load3(in []byte) int64 { - var r int64 - r = int64(in[0]) - r |= int64(in[1]) << 8 - r |= int64(in[2]) << 16 - return r -} - -func load4(in []byte) int64 { - var r int64 - r = int64(in[0]) - r |= int64(in[1]) << 8 - r |= int64(in[2]) << 16 - r |= int64(in[3]) << 24 - return r -} - -func FeFromBytes(dst *FieldElement, src *[32]byte) { - h0 := load4(src[:]) - h1 := load3(src[4:]) << 6 - h2 := load3(src[7:]) << 5 - h3 := load3(src[10:]) << 3 - h4 := load3(src[13:]) << 2 - h5 := load4(src[16:]) - h6 := load3(src[20:]) << 7 - h7 := load3(src[23:]) << 5 - h8 := load3(src[26:]) << 4 - h9 := (load3(src[29:]) & 8388607) << 2 - - FeCombine(dst, h0, h1, h2, h3, h4, h5, h6, h7, h8, h9) -} - -// FeToBytes marshals h to s. -// Preconditions: -// |h| bounded by 1.1*2^25,1.1*2^24,1.1*2^25,1.1*2^24,etc. -// -// Write p=2^255-19; q=floor(h/p). -// Basic claim: q = floor(2^(-255)(h + 19 2^(-25)h9 + 2^(-1))). -// -// Proof: -// Have |h|<=p so |q|<=1 so |19^2 2^(-255) q|<1/4. -// Also have |h-2^230 h9|<2^230 so |19 2^(-255)(h-2^230 h9)|<1/4. -// -// Write y=2^(-1)-19^2 2^(-255)q-19 2^(-255)(h-2^230 h9). -// Then 0> 25 - q = (h[0] + q) >> 26 - q = (h[1] + q) >> 25 - q = (h[2] + q) >> 26 - q = (h[3] + q) >> 25 - q = (h[4] + q) >> 26 - q = (h[5] + q) >> 25 - q = (h[6] + q) >> 26 - q = (h[7] + q) >> 25 - q = (h[8] + q) >> 26 - q = (h[9] + q) >> 25 - - // Goal: Output h-(2^255-19)q, which is between 0 and 2^255-20. - h[0] += 19 * q - // Goal: Output h-2^255 q, which is between 0 and 2^255-20. - - carry[0] = h[0] >> 26 - h[1] += carry[0] - h[0] -= carry[0] << 26 - carry[1] = h[1] >> 25 - h[2] += carry[1] - h[1] -= carry[1] << 25 - carry[2] = h[2] >> 26 - h[3] += carry[2] - h[2] -= carry[2] << 26 - carry[3] = h[3] >> 25 - h[4] += carry[3] - h[3] -= carry[3] << 25 - carry[4] = h[4] >> 26 - h[5] += carry[4] - h[4] -= carry[4] << 26 - carry[5] = h[5] >> 25 - h[6] += carry[5] - h[5] -= carry[5] << 25 - carry[6] = h[6] >> 26 - h[7] += carry[6] - h[6] -= carry[6] << 26 - carry[7] = h[7] >> 25 - h[8] += carry[7] - h[7] -= carry[7] << 25 - carry[8] = h[8] >> 26 - h[9] += carry[8] - h[8] -= carry[8] << 26 - carry[9] = h[9] >> 25 - h[9] -= carry[9] << 25 - // h10 = carry9 - - // Goal: Output h[0]+...+2^255 h10-2^255 q, which is between 0 and 2^255-20. - // Have h[0]+...+2^230 h[9] between 0 and 2^255-1; - // evidently 2^255 h10-2^255 q = 0. - // Goal: Output h[0]+...+2^230 h[9]. - - s[0] = byte(h[0] >> 0) - s[1] = byte(h[0] >> 8) - s[2] = byte(h[0] >> 16) - s[3] = byte((h[0] >> 24) | (h[1] << 2)) - s[4] = byte(h[1] >> 6) - s[5] = byte(h[1] >> 14) - s[6] = byte((h[1] >> 22) | (h[2] << 3)) - s[7] = byte(h[2] >> 5) - s[8] = byte(h[2] >> 13) - s[9] = byte((h[2] >> 21) | (h[3] << 5)) - s[10] = byte(h[3] >> 3) - s[11] = byte(h[3] >> 11) - s[12] = byte((h[3] >> 19) | (h[4] << 6)) - s[13] = byte(h[4] >> 2) - s[14] = byte(h[4] >> 10) - s[15] = byte(h[4] >> 18) - s[16] = byte(h[5] >> 0) - s[17] = byte(h[5] >> 8) - s[18] = byte(h[5] >> 16) - s[19] = byte((h[5] >> 24) | (h[6] << 1)) - s[20] = byte(h[6] >> 7) - s[21] = byte(h[6] >> 15) - s[22] = byte((h[6] >> 23) | (h[7] << 3)) - s[23] = byte(h[7] >> 5) - s[24] = byte(h[7] >> 13) - s[25] = byte((h[7] >> 21) | (h[8] << 4)) - s[26] = byte(h[8] >> 4) - s[27] = byte(h[8] >> 12) - s[28] = byte((h[8] >> 20) | (h[9] << 6)) - s[29] = byte(h[9] >> 2) - s[30] = byte(h[9] >> 10) - s[31] = byte(h[9] >> 18) -} - -func FeIsNegative(f *FieldElement) byte { - var s [32]byte - FeToBytes(&s, f) - return s[0] & 1 -} - -func FeIsNonZero(f *FieldElement) int32 { - var s [32]byte - FeToBytes(&s, f) - var x uint8 - for _, b := range s { - x |= b - } - x |= x >> 4 - x |= x >> 2 - x |= x >> 1 - return int32(x & 1) -} - -// FeNeg sets h = -f -// -// Preconditions: -// |f| bounded by 1.1*2^25,1.1*2^24,1.1*2^25,1.1*2^24,etc. -// -// Postconditions: -// |h| bounded by 1.1*2^25,1.1*2^24,1.1*2^25,1.1*2^24,etc. -func FeNeg(h, f *FieldElement) { - h[0] = -f[0] - h[1] = -f[1] - h[2] = -f[2] - h[3] = -f[3] - h[4] = -f[4] - h[5] = -f[5] - h[6] = -f[6] - h[7] = -f[7] - h[8] = -f[8] - h[9] = -f[9] -} - -func FeCombine(h *FieldElement, h0, h1, h2, h3, h4, h5, h6, h7, h8, h9 int64) { - var c0, c1, c2, c3, c4, c5, c6, c7, c8, c9 int64 - - /* - |h0| <= (1.1*1.1*2^52*(1+19+19+19+19)+1.1*1.1*2^50*(38+38+38+38+38)) - i.e. |h0| <= 1.2*2^59; narrower ranges for h2, h4, h6, h8 - |h1| <= (1.1*1.1*2^51*(1+1+19+19+19+19+19+19+19+19)) - i.e. |h1| <= 1.5*2^58; narrower ranges for h3, h5, h7, h9 - */ - - c0 = (h0 + (1 << 25)) >> 26 - h1 += c0 - h0 -= c0 << 26 - c4 = (h4 + (1 << 25)) >> 26 - h5 += c4 - h4 -= c4 << 26 - /* |h0| <= 2^25 */ - /* |h4| <= 2^25 */ - /* |h1| <= 1.51*2^58 */ - /* |h5| <= 1.51*2^58 */ - - c1 = (h1 + (1 << 24)) >> 25 - h2 += c1 - h1 -= c1 << 25 - c5 = (h5 + (1 << 24)) >> 25 - h6 += c5 - h5 -= c5 << 25 - /* |h1| <= 2^24; from now on fits into int32 */ - /* |h5| <= 2^24; from now on fits into int32 */ - /* |h2| <= 1.21*2^59 */ - /* |h6| <= 1.21*2^59 */ - - c2 = (h2 + (1 << 25)) >> 26 - h3 += c2 - h2 -= c2 << 26 - c6 = (h6 + (1 << 25)) >> 26 - h7 += c6 - h6 -= c6 << 26 - /* |h2| <= 2^25; from now on fits into int32 unchanged */ - /* |h6| <= 2^25; from now on fits into int32 unchanged */ - /* |h3| <= 1.51*2^58 */ - /* |h7| <= 1.51*2^58 */ - - c3 = (h3 + (1 << 24)) >> 25 - h4 += c3 - h3 -= c3 << 25 - c7 = (h7 + (1 << 24)) >> 25 - h8 += c7 - h7 -= c7 << 25 - /* |h3| <= 2^24; from now on fits into int32 unchanged */ - /* |h7| <= 2^24; from now on fits into int32 unchanged */ - /* |h4| <= 1.52*2^33 */ - /* |h8| <= 1.52*2^33 */ - - c4 = (h4 + (1 << 25)) >> 26 - h5 += c4 - h4 -= c4 << 26 - c8 = (h8 + (1 << 25)) >> 26 - h9 += c8 - h8 -= c8 << 26 - /* |h4| <= 2^25; from now on fits into int32 unchanged */ - /* |h8| <= 2^25; from now on fits into int32 unchanged */ - /* |h5| <= 1.01*2^24 */ - /* |h9| <= 1.51*2^58 */ - - c9 = (h9 + (1 << 24)) >> 25 - h0 += c9 * 19 - h9 -= c9 << 25 - /* |h9| <= 2^24; from now on fits into int32 unchanged */ - /* |h0| <= 1.8*2^37 */ - - c0 = (h0 + (1 << 25)) >> 26 - h1 += c0 - h0 -= c0 << 26 - /* |h0| <= 2^25; from now on fits into int32 unchanged */ - /* |h1| <= 1.01*2^24 */ - - h[0] = int32(h0) - h[1] = int32(h1) - h[2] = int32(h2) - h[3] = int32(h3) - h[4] = int32(h4) - h[5] = int32(h5) - h[6] = int32(h6) - h[7] = int32(h7) - h[8] = int32(h8) - h[9] = int32(h9) -} - -// FeMul calculates h = f * g -// Can overlap h with f or g. -// -// Preconditions: -// |f| bounded by 1.1*2^26,1.1*2^25,1.1*2^26,1.1*2^25,etc. -// |g| bounded by 1.1*2^26,1.1*2^25,1.1*2^26,1.1*2^25,etc. -// -// Postconditions: -// |h| bounded by 1.1*2^25,1.1*2^24,1.1*2^25,1.1*2^24,etc. -// -// Notes on implementation strategy: -// -// Using schoolbook multiplication. -// Karatsuba would save a little in some cost models. -// -// Most multiplications by 2 and 19 are 32-bit precomputations; -// cheaper than 64-bit postcomputations. -// -// There is one remaining multiplication by 19 in the carry chain; -// one *19 precomputation can be merged into this, -// but the resulting data flow is considerably less clean. -// -// There are 12 carries below. -// 10 of them are 2-way parallelizable and vectorizable. -// Can get away with 11 carries, but then data flow is much deeper. -// -// With tighter constraints on inputs, can squeeze carries into int32. -func FeMul(h, f, g *FieldElement) { - f0 := int64(f[0]) - f1 := int64(f[1]) - f2 := int64(f[2]) - f3 := int64(f[3]) - f4 := int64(f[4]) - f5 := int64(f[5]) - f6 := int64(f[6]) - f7 := int64(f[7]) - f8 := int64(f[8]) - f9 := int64(f[9]) - - f1_2 := int64(2 * f[1]) - f3_2 := int64(2 * f[3]) - f5_2 := int64(2 * f[5]) - f7_2 := int64(2 * f[7]) - f9_2 := int64(2 * f[9]) - - g0 := int64(g[0]) - g1 := int64(g[1]) - g2 := int64(g[2]) - g3 := int64(g[3]) - g4 := int64(g[4]) - g5 := int64(g[5]) - g6 := int64(g[6]) - g7 := int64(g[7]) - g8 := int64(g[8]) - g9 := int64(g[9]) - - g1_19 := int64(19 * g[1]) /* 1.4*2^29 */ - g2_19 := int64(19 * g[2]) /* 1.4*2^30; still ok */ - g3_19 := int64(19 * g[3]) - g4_19 := int64(19 * g[4]) - g5_19 := int64(19 * g[5]) - g6_19 := int64(19 * g[6]) - g7_19 := int64(19 * g[7]) - g8_19 := int64(19 * g[8]) - g9_19 := int64(19 * g[9]) - - h0 := f0*g0 + f1_2*g9_19 + f2*g8_19 + f3_2*g7_19 + f4*g6_19 + f5_2*g5_19 + f6*g4_19 + f7_2*g3_19 + f8*g2_19 + f9_2*g1_19 - h1 := f0*g1 + f1*g0 + f2*g9_19 + f3*g8_19 + f4*g7_19 + f5*g6_19 + f6*g5_19 + f7*g4_19 + f8*g3_19 + f9*g2_19 - h2 := f0*g2 + f1_2*g1 + f2*g0 + f3_2*g9_19 + f4*g8_19 + f5_2*g7_19 + f6*g6_19 + f7_2*g5_19 + f8*g4_19 + f9_2*g3_19 - h3 := f0*g3 + f1*g2 + f2*g1 + f3*g0 + f4*g9_19 + f5*g8_19 + f6*g7_19 + f7*g6_19 + f8*g5_19 + f9*g4_19 - h4 := f0*g4 + f1_2*g3 + f2*g2 + f3_2*g1 + f4*g0 + f5_2*g9_19 + f6*g8_19 + f7_2*g7_19 + f8*g6_19 + f9_2*g5_19 - h5 := f0*g5 + f1*g4 + f2*g3 + f3*g2 + f4*g1 + f5*g0 + f6*g9_19 + f7*g8_19 + f8*g7_19 + f9*g6_19 - h6 := f0*g6 + f1_2*g5 + f2*g4 + f3_2*g3 + f4*g2 + f5_2*g1 + f6*g0 + f7_2*g9_19 + f8*g8_19 + f9_2*g7_19 - h7 := f0*g7 + f1*g6 + f2*g5 + f3*g4 + f4*g3 + f5*g2 + f6*g1 + f7*g0 + f8*g9_19 + f9*g8_19 - h8 := f0*g8 + f1_2*g7 + f2*g6 + f3_2*g5 + f4*g4 + f5_2*g3 + f6*g2 + f7_2*g1 + f8*g0 + f9_2*g9_19 - h9 := f0*g9 + f1*g8 + f2*g7 + f3*g6 + f4*g5 + f5*g4 + f6*g3 + f7*g2 + f8*g1 + f9*g0 - - FeCombine(h, h0, h1, h2, h3, h4, h5, h6, h7, h8, h9) -} - -func feSquare(f *FieldElement) (h0, h1, h2, h3, h4, h5, h6, h7, h8, h9 int64) { - f0 := int64(f[0]) - f1 := int64(f[1]) - f2 := int64(f[2]) - f3 := int64(f[3]) - f4 := int64(f[4]) - f5 := int64(f[5]) - f6 := int64(f[6]) - f7 := int64(f[7]) - f8 := int64(f[8]) - f9 := int64(f[9]) - f0_2 := int64(2 * f[0]) - f1_2 := int64(2 * f[1]) - f2_2 := int64(2 * f[2]) - f3_2 := int64(2 * f[3]) - f4_2 := int64(2 * f[4]) - f5_2 := int64(2 * f[5]) - f6_2 := int64(2 * f[6]) - f7_2 := int64(2 * f[7]) - f5_38 := 38 * f5 // 1.31*2^30 - f6_19 := 19 * f6 // 1.31*2^30 - f7_38 := 38 * f7 // 1.31*2^30 - f8_19 := 19 * f8 // 1.31*2^30 - f9_38 := 38 * f9 // 1.31*2^30 - - h0 = f0*f0 + f1_2*f9_38 + f2_2*f8_19 + f3_2*f7_38 + f4_2*f6_19 + f5*f5_38 - h1 = f0_2*f1 + f2*f9_38 + f3_2*f8_19 + f4*f7_38 + f5_2*f6_19 - h2 = f0_2*f2 + f1_2*f1 + f3_2*f9_38 + f4_2*f8_19 + f5_2*f7_38 + f6*f6_19 - h3 = f0_2*f3 + f1_2*f2 + f4*f9_38 + f5_2*f8_19 + f6*f7_38 - h4 = f0_2*f4 + f1_2*f3_2 + f2*f2 + f5_2*f9_38 + f6_2*f8_19 + f7*f7_38 - h5 = f0_2*f5 + f1_2*f4 + f2_2*f3 + f6*f9_38 + f7_2*f8_19 - h6 = f0_2*f6 + f1_2*f5_2 + f2_2*f4 + f3_2*f3 + f7_2*f9_38 + f8*f8_19 - h7 = f0_2*f7 + f1_2*f6 + f2_2*f5 + f3_2*f4 + f8*f9_38 - h8 = f0_2*f8 + f1_2*f7_2 + f2_2*f6 + f3_2*f5_2 + f4*f4 + f9*f9_38 - h9 = f0_2*f9 + f1_2*f8 + f2_2*f7 + f3_2*f6 + f4_2*f5 - - return -} - -// FeSquare calculates h = f*f. Can overlap h with f. -// -// Preconditions: -// |f| bounded by 1.1*2^26,1.1*2^25,1.1*2^26,1.1*2^25,etc. -// -// Postconditions: -// |h| bounded by 1.1*2^25,1.1*2^24,1.1*2^25,1.1*2^24,etc. -func FeSquare(h, f *FieldElement) { - h0, h1, h2, h3, h4, h5, h6, h7, h8, h9 := feSquare(f) - FeCombine(h, h0, h1, h2, h3, h4, h5, h6, h7, h8, h9) -} - -// FeSquare2 sets h = 2 * f * f -// -// Can overlap h with f. -// -// Preconditions: -// |f| bounded by 1.65*2^26,1.65*2^25,1.65*2^26,1.65*2^25,etc. -// -// Postconditions: -// |h| bounded by 1.01*2^25,1.01*2^24,1.01*2^25,1.01*2^24,etc. -// See fe_mul.c for discussion of implementation strategy. -func FeSquare2(h, f *FieldElement) { - h0, h1, h2, h3, h4, h5, h6, h7, h8, h9 := feSquare(f) - - h0 += h0 - h1 += h1 - h2 += h2 - h3 += h3 - h4 += h4 - h5 += h5 - h6 += h6 - h7 += h7 - h8 += h8 - h9 += h9 - - FeCombine(h, h0, h1, h2, h3, h4, h5, h6, h7, h8, h9) -} - -func FeInvert(out, z *FieldElement) { - var t0, t1, t2, t3 FieldElement - var i int - - FeSquare(&t0, z) // 2^1 - FeSquare(&t1, &t0) // 2^2 - for i = 1; i < 2; i++ { // 2^3 - FeSquare(&t1, &t1) - } - FeMul(&t1, z, &t1) // 2^3 + 2^0 - FeMul(&t0, &t0, &t1) // 2^3 + 2^1 + 2^0 - FeSquare(&t2, &t0) // 2^4 + 2^2 + 2^1 - FeMul(&t1, &t1, &t2) // 2^4 + 2^3 + 2^2 + 2^1 + 2^0 - FeSquare(&t2, &t1) // 5,4,3,2,1 - for i = 1; i < 5; i++ { // 9,8,7,6,5 - FeSquare(&t2, &t2) - } - FeMul(&t1, &t2, &t1) // 9,8,7,6,5,4,3,2,1,0 - FeSquare(&t2, &t1) // 10..1 - for i = 1; i < 10; i++ { // 19..10 - FeSquare(&t2, &t2) - } - FeMul(&t2, &t2, &t1) // 19..0 - FeSquare(&t3, &t2) // 20..1 - for i = 1; i < 20; i++ { // 39..20 - FeSquare(&t3, &t3) - } - FeMul(&t2, &t3, &t2) // 39..0 - FeSquare(&t2, &t2) // 40..1 - for i = 1; i < 10; i++ { // 49..10 - FeSquare(&t2, &t2) - } - FeMul(&t1, &t2, &t1) // 49..0 - FeSquare(&t2, &t1) // 50..1 - for i = 1; i < 50; i++ { // 99..50 - FeSquare(&t2, &t2) - } - FeMul(&t2, &t2, &t1) // 99..0 - FeSquare(&t3, &t2) // 100..1 - for i = 1; i < 100; i++ { // 199..100 - FeSquare(&t3, &t3) - } - FeMul(&t2, &t3, &t2) // 199..0 - FeSquare(&t2, &t2) // 200..1 - for i = 1; i < 50; i++ { // 249..50 - FeSquare(&t2, &t2) - } - FeMul(&t1, &t2, &t1) // 249..0 - FeSquare(&t1, &t1) // 250..1 - for i = 1; i < 5; i++ { // 254..5 - FeSquare(&t1, &t1) - } - FeMul(out, &t1, &t0) // 254..5,3,1,0 -} - -func fePow22523(out, z *FieldElement) { - var t0, t1, t2 FieldElement - var i int - - FeSquare(&t0, z) - for i = 1; i < 1; i++ { - FeSquare(&t0, &t0) - } - FeSquare(&t1, &t0) - for i = 1; i < 2; i++ { - FeSquare(&t1, &t1) - } - FeMul(&t1, z, &t1) - FeMul(&t0, &t0, &t1) - FeSquare(&t0, &t0) - for i = 1; i < 1; i++ { - FeSquare(&t0, &t0) - } - FeMul(&t0, &t1, &t0) - FeSquare(&t1, &t0) - for i = 1; i < 5; i++ { - FeSquare(&t1, &t1) - } - FeMul(&t0, &t1, &t0) - FeSquare(&t1, &t0) - for i = 1; i < 10; i++ { - FeSquare(&t1, &t1) - } - FeMul(&t1, &t1, &t0) - FeSquare(&t2, &t1) - for i = 1; i < 20; i++ { - FeSquare(&t2, &t2) - } - FeMul(&t1, &t2, &t1) - FeSquare(&t1, &t1) - for i = 1; i < 10; i++ { - FeSquare(&t1, &t1) - } - FeMul(&t0, &t1, &t0) - FeSquare(&t1, &t0) - for i = 1; i < 50; i++ { - FeSquare(&t1, &t1) - } - FeMul(&t1, &t1, &t0) - FeSquare(&t2, &t1) - for i = 1; i < 100; i++ { - FeSquare(&t2, &t2) - } - FeMul(&t1, &t2, &t1) - FeSquare(&t1, &t1) - for i = 1; i < 50; i++ { - FeSquare(&t1, &t1) - } - FeMul(&t0, &t1, &t0) - FeSquare(&t0, &t0) - for i = 1; i < 2; i++ { - FeSquare(&t0, &t0) - } - FeMul(out, &t0, z) -} - -// Group elements are members of the elliptic curve -x^2 + y^2 = 1 + d * x^2 * -// y^2 where d = -121665/121666. -// -// Several representations are used: -// ProjectiveGroupElement: (X:Y:Z) satisfying x=X/Z, y=Y/Z -// ExtendedGroupElement: (X:Y:Z:T) satisfying x=X/Z, y=Y/Z, XY=ZT -// CompletedGroupElement: ((X:Z),(Y:T)) satisfying x=X/Z, y=Y/T -// PreComputedGroupElement: (y+x,y-x,2dxy) - -type ProjectiveGroupElement struct { - X, Y, Z FieldElement -} - -type ExtendedGroupElement struct { - X, Y, Z, T FieldElement -} - -type CompletedGroupElement struct { - X, Y, Z, T FieldElement -} - -type PreComputedGroupElement struct { - yPlusX, yMinusX, xy2d FieldElement -} - -type CachedGroupElement struct { - yPlusX, yMinusX, Z, T2d FieldElement -} - -func (p *ProjectiveGroupElement) Zero() { - FeZero(&p.X) - FeOne(&p.Y) - FeOne(&p.Z) -} - -func (p *ProjectiveGroupElement) Double(r *CompletedGroupElement) { - var t0 FieldElement - - FeSquare(&r.X, &p.X) - FeSquare(&r.Z, &p.Y) - FeSquare2(&r.T, &p.Z) - FeAdd(&r.Y, &p.X, &p.Y) - FeSquare(&t0, &r.Y) - FeAdd(&r.Y, &r.Z, &r.X) - FeSub(&r.Z, &r.Z, &r.X) - FeSub(&r.X, &t0, &r.Y) - FeSub(&r.T, &r.T, &r.Z) -} - -func (p *ProjectiveGroupElement) ToBytes(s *[32]byte) { - var recip, x, y FieldElement - - FeInvert(&recip, &p.Z) - FeMul(&x, &p.X, &recip) - FeMul(&y, &p.Y, &recip) - FeToBytes(s, &y) - s[31] ^= FeIsNegative(&x) << 7 -} - -func (p *ExtendedGroupElement) Zero() { - FeZero(&p.X) - FeOne(&p.Y) - FeOne(&p.Z) - FeZero(&p.T) -} - -func (p *ExtendedGroupElement) Double(r *CompletedGroupElement) { - var q ProjectiveGroupElement - p.ToProjective(&q) - q.Double(r) -} - -func (p *ExtendedGroupElement) ToCached(r *CachedGroupElement) { - FeAdd(&r.yPlusX, &p.Y, &p.X) - FeSub(&r.yMinusX, &p.Y, &p.X) - FeCopy(&r.Z, &p.Z) - FeMul(&r.T2d, &p.T, &d2) -} - -func (p *ExtendedGroupElement) ToProjective(r *ProjectiveGroupElement) { - FeCopy(&r.X, &p.X) - FeCopy(&r.Y, &p.Y) - FeCopy(&r.Z, &p.Z) -} - -func (p *ExtendedGroupElement) ToBytes(s *[32]byte) { - var recip, x, y FieldElement - - FeInvert(&recip, &p.Z) - FeMul(&x, &p.X, &recip) - FeMul(&y, &p.Y, &recip) - FeToBytes(s, &y) - s[31] ^= FeIsNegative(&x) << 7 -} - -func (p *ExtendedGroupElement) FromBytes(s *[32]byte) bool { - var u, v, v3, vxx, check FieldElement - - FeFromBytes(&p.Y, s) - FeOne(&p.Z) - FeSquare(&u, &p.Y) - FeMul(&v, &u, &d) - FeSub(&u, &u, &p.Z) // y = y^2-1 - FeAdd(&v, &v, &p.Z) // v = dy^2+1 - - FeSquare(&v3, &v) - FeMul(&v3, &v3, &v) // v3 = v^3 - FeSquare(&p.X, &v3) - FeMul(&p.X, &p.X, &v) - FeMul(&p.X, &p.X, &u) // x = uv^7 - - fePow22523(&p.X, &p.X) // x = (uv^7)^((q-5)/8) - FeMul(&p.X, &p.X, &v3) - FeMul(&p.X, &p.X, &u) // x = uv^3(uv^7)^((q-5)/8) - - var tmpX, tmp2 [32]byte - - FeSquare(&vxx, &p.X) - FeMul(&vxx, &vxx, &v) - FeSub(&check, &vxx, &u) // vx^2-u - if FeIsNonZero(&check) == 1 { - FeAdd(&check, &vxx, &u) // vx^2+u - if FeIsNonZero(&check) == 1 { - return false - } - FeMul(&p.X, &p.X, &SqrtM1) - - FeToBytes(&tmpX, &p.X) - for i, v := range tmpX { - tmp2[31-i] = v - } - } - - if FeIsNegative(&p.X) != (s[31] >> 7) { - FeNeg(&p.X, &p.X) - } - - FeMul(&p.T, &p.X, &p.Y) - return true -} - -func (p *CompletedGroupElement) ToProjective(r *ProjectiveGroupElement) { - FeMul(&r.X, &p.X, &p.T) - FeMul(&r.Y, &p.Y, &p.Z) - FeMul(&r.Z, &p.Z, &p.T) -} - -func (p *CompletedGroupElement) ToExtended(r *ExtendedGroupElement) { - FeMul(&r.X, &p.X, &p.T) - FeMul(&r.Y, &p.Y, &p.Z) - FeMul(&r.Z, &p.Z, &p.T) - FeMul(&r.T, &p.X, &p.Y) -} - -func (p *PreComputedGroupElement) Zero() { - FeOne(&p.yPlusX) - FeOne(&p.yMinusX) - FeZero(&p.xy2d) -} - -func geAdd(r *CompletedGroupElement, p *ExtendedGroupElement, q *CachedGroupElement) { - var t0 FieldElement - - FeAdd(&r.X, &p.Y, &p.X) - FeSub(&r.Y, &p.Y, &p.X) - FeMul(&r.Z, &r.X, &q.yPlusX) - FeMul(&r.Y, &r.Y, &q.yMinusX) - FeMul(&r.T, &q.T2d, &p.T) - FeMul(&r.X, &p.Z, &q.Z) - FeAdd(&t0, &r.X, &r.X) - FeSub(&r.X, &r.Z, &r.Y) - FeAdd(&r.Y, &r.Z, &r.Y) - FeAdd(&r.Z, &t0, &r.T) - FeSub(&r.T, &t0, &r.T) -} - -func geSub(r *CompletedGroupElement, p *ExtendedGroupElement, q *CachedGroupElement) { - var t0 FieldElement - - FeAdd(&r.X, &p.Y, &p.X) - FeSub(&r.Y, &p.Y, &p.X) - FeMul(&r.Z, &r.X, &q.yMinusX) - FeMul(&r.Y, &r.Y, &q.yPlusX) - FeMul(&r.T, &q.T2d, &p.T) - FeMul(&r.X, &p.Z, &q.Z) - FeAdd(&t0, &r.X, &r.X) - FeSub(&r.X, &r.Z, &r.Y) - FeAdd(&r.Y, &r.Z, &r.Y) - FeSub(&r.Z, &t0, &r.T) - FeAdd(&r.T, &t0, &r.T) -} - -func geMixedAdd(r *CompletedGroupElement, p *ExtendedGroupElement, q *PreComputedGroupElement) { - var t0 FieldElement - - FeAdd(&r.X, &p.Y, &p.X) - FeSub(&r.Y, &p.Y, &p.X) - FeMul(&r.Z, &r.X, &q.yPlusX) - FeMul(&r.Y, &r.Y, &q.yMinusX) - FeMul(&r.T, &q.xy2d, &p.T) - FeAdd(&t0, &p.Z, &p.Z) - FeSub(&r.X, &r.Z, &r.Y) - FeAdd(&r.Y, &r.Z, &r.Y) - FeAdd(&r.Z, &t0, &r.T) - FeSub(&r.T, &t0, &r.T) -} - -func geMixedSub(r *CompletedGroupElement, p *ExtendedGroupElement, q *PreComputedGroupElement) { - var t0 FieldElement - - FeAdd(&r.X, &p.Y, &p.X) - FeSub(&r.Y, &p.Y, &p.X) - FeMul(&r.Z, &r.X, &q.yMinusX) - FeMul(&r.Y, &r.Y, &q.yPlusX) - FeMul(&r.T, &q.xy2d, &p.T) - FeAdd(&t0, &p.Z, &p.Z) - FeSub(&r.X, &r.Z, &r.Y) - FeAdd(&r.Y, &r.Z, &r.Y) - FeSub(&r.Z, &t0, &r.T) - FeAdd(&r.T, &t0, &r.T) -} - -func slide(r *[256]int8, a *[32]byte) { - for i := range r { - r[i] = int8(1 & (a[i>>3] >> uint(i&7))) - } - - for i := range r { - if r[i] != 0 { - for b := 1; b <= 6 && i+b < 256; b++ { - if r[i+b] != 0 { - if r[i]+(r[i+b]<= -15 { - r[i] -= r[i+b] << uint(b) - for k := i + b; k < 256; k++ { - if r[k] == 0 { - r[k] = 1 - break - } - r[k] = 0 - } - } else { - break - } - } - } - } - } -} - -// GeDoubleScalarMultVartime sets r = a*A + b*B -// where a = a[0]+256*a[1]+...+256^31 a[31]. -// and b = b[0]+256*b[1]+...+256^31 b[31]. -// B is the Ed25519 base point (x,4/5) with x positive. -func GeDoubleScalarMultVartime(r *ProjectiveGroupElement, a *[32]byte, A *ExtendedGroupElement, b *[32]byte) { - var aSlide, bSlide [256]int8 - var Ai [8]CachedGroupElement // A,3A,5A,7A,9A,11A,13A,15A - var t CompletedGroupElement - var u, A2 ExtendedGroupElement - var i int - - slide(&aSlide, a) - slide(&bSlide, b) - - A.ToCached(&Ai[0]) - A.Double(&t) - t.ToExtended(&A2) - - for i := 0; i < 7; i++ { - geAdd(&t, &A2, &Ai[i]) - t.ToExtended(&u) - u.ToCached(&Ai[i+1]) - } - - r.Zero() - - for i = 255; i >= 0; i-- { - if aSlide[i] != 0 || bSlide[i] != 0 { - break - } - } - - for ; i >= 0; i-- { - r.Double(&t) - - if aSlide[i] > 0 { - t.ToExtended(&u) - geAdd(&t, &u, &Ai[aSlide[i]/2]) - } else if aSlide[i] < 0 { - t.ToExtended(&u) - geSub(&t, &u, &Ai[(-aSlide[i])/2]) - } - - if bSlide[i] > 0 { - t.ToExtended(&u) - geMixedAdd(&t, &u, &bi[bSlide[i]/2]) - } else if bSlide[i] < 0 { - t.ToExtended(&u) - geMixedSub(&t, &u, &bi[(-bSlide[i])/2]) - } - - t.ToProjective(r) - } -} - -// equal returns 1 if b == c and 0 otherwise, assuming that b and c are -// non-negative. -func equal(b, c int32) int32 { - x := uint32(b ^ c) - x-- - return int32(x >> 31) -} - -// negative returns 1 if b < 0 and 0 otherwise. -func negative(b int32) int32 { - return (b >> 31) & 1 -} - -func PreComputedGroupElementCMove(t, u *PreComputedGroupElement, b int32) { - FeCMove(&t.yPlusX, &u.yPlusX, b) - FeCMove(&t.yMinusX, &u.yMinusX, b) - FeCMove(&t.xy2d, &u.xy2d, b) -} - -func selectPoint(t *PreComputedGroupElement, pos int32, b int32) { - var minusT PreComputedGroupElement - bNegative := negative(b) - bAbs := b - (((-bNegative) & b) << 1) - - t.Zero() - for i := int32(0); i < 8; i++ { - PreComputedGroupElementCMove(t, &base[pos][i], equal(bAbs, i+1)) - } - FeCopy(&minusT.yPlusX, &t.yMinusX) - FeCopy(&minusT.yMinusX, &t.yPlusX) - FeNeg(&minusT.xy2d, &t.xy2d) - PreComputedGroupElementCMove(t, &minusT, bNegative) -} - -// GeScalarMultBase computes h = a*B, where -// a = a[0]+256*a[1]+...+256^31 a[31] -// B is the Ed25519 base point (x,4/5) with x positive. -// -// Preconditions: -// a[31] <= 127 -func GeScalarMultBase(h *ExtendedGroupElement, a *[32]byte) { - var e [64]int8 - - for i, v := range a { - e[2*i] = int8(v & 15) - e[2*i+1] = int8((v >> 4) & 15) - } - - // each e[i] is between 0 and 15 and e[63] is between 0 and 7. - - carry := int8(0) - for i := 0; i < 63; i++ { - e[i] += carry - carry = (e[i] + 8) >> 4 - e[i] -= carry << 4 - } - e[63] += carry - // each e[i] is between -8 and 8. - - h.Zero() - var t PreComputedGroupElement - var r CompletedGroupElement - for i := int32(1); i < 64; i += 2 { - selectPoint(&t, i/2, int32(e[i])) - geMixedAdd(&r, h, &t) - r.ToExtended(h) - } - - var s ProjectiveGroupElement - - h.Double(&r) - r.ToProjective(&s) - s.Double(&r) - r.ToProjective(&s) - s.Double(&r) - r.ToProjective(&s) - s.Double(&r) - r.ToExtended(h) - - for i := int32(0); i < 64; i += 2 { - selectPoint(&t, i/2, int32(e[i])) - geMixedAdd(&r, h, &t) - r.ToExtended(h) - } -} - -// The scalars are GF(2^252 + 27742317777372353535851937790883648493). - -// Input: -// a[0]+256*a[1]+...+256^31*a[31] = a -// b[0]+256*b[1]+...+256^31*b[31] = b -// c[0]+256*c[1]+...+256^31*c[31] = c -// -// Output: -// s[0]+256*s[1]+...+256^31*s[31] = (ab+c) mod l -// where l = 2^252 + 27742317777372353535851937790883648493. -func ScMulAdd(s, a, b, c *[32]byte) { - a0 := 2097151 & load3(a[:]) - a1 := 2097151 & (load4(a[2:]) >> 5) - a2 := 2097151 & (load3(a[5:]) >> 2) - a3 := 2097151 & (load4(a[7:]) >> 7) - a4 := 2097151 & (load4(a[10:]) >> 4) - a5 := 2097151 & (load3(a[13:]) >> 1) - a6 := 2097151 & (load4(a[15:]) >> 6) - a7 := 2097151 & (load3(a[18:]) >> 3) - a8 := 2097151 & load3(a[21:]) - a9 := 2097151 & (load4(a[23:]) >> 5) - a10 := 2097151 & (load3(a[26:]) >> 2) - a11 := (load4(a[28:]) >> 7) - b0 := 2097151 & load3(b[:]) - b1 := 2097151 & (load4(b[2:]) >> 5) - b2 := 2097151 & (load3(b[5:]) >> 2) - b3 := 2097151 & (load4(b[7:]) >> 7) - b4 := 2097151 & (load4(b[10:]) >> 4) - b5 := 2097151 & (load3(b[13:]) >> 1) - b6 := 2097151 & (load4(b[15:]) >> 6) - b7 := 2097151 & (load3(b[18:]) >> 3) - b8 := 2097151 & load3(b[21:]) - b9 := 2097151 & (load4(b[23:]) >> 5) - b10 := 2097151 & (load3(b[26:]) >> 2) - b11 := (load4(b[28:]) >> 7) - c0 := 2097151 & load3(c[:]) - c1 := 2097151 & (load4(c[2:]) >> 5) - c2 := 2097151 & (load3(c[5:]) >> 2) - c3 := 2097151 & (load4(c[7:]) >> 7) - c4 := 2097151 & (load4(c[10:]) >> 4) - c5 := 2097151 & (load3(c[13:]) >> 1) - c6 := 2097151 & (load4(c[15:]) >> 6) - c7 := 2097151 & (load3(c[18:]) >> 3) - c8 := 2097151 & load3(c[21:]) - c9 := 2097151 & (load4(c[23:]) >> 5) - c10 := 2097151 & (load3(c[26:]) >> 2) - c11 := (load4(c[28:]) >> 7) - var carry [23]int64 - - s0 := c0 + a0*b0 - s1 := c1 + a0*b1 + a1*b0 - s2 := c2 + a0*b2 + a1*b1 + a2*b0 - s3 := c3 + a0*b3 + a1*b2 + a2*b1 + a3*b0 - s4 := c4 + a0*b4 + a1*b3 + a2*b2 + a3*b1 + a4*b0 - s5 := c5 + a0*b5 + a1*b4 + a2*b3 + a3*b2 + a4*b1 + a5*b0 - s6 := c6 + a0*b6 + a1*b5 + a2*b4 + a3*b3 + a4*b2 + a5*b1 + a6*b0 - s7 := c7 + a0*b7 + a1*b6 + a2*b5 + a3*b4 + a4*b3 + a5*b2 + a6*b1 + a7*b0 - s8 := c8 + a0*b8 + a1*b7 + a2*b6 + a3*b5 + a4*b4 + a5*b3 + a6*b2 + a7*b1 + a8*b0 - s9 := c9 + a0*b9 + a1*b8 + a2*b7 + a3*b6 + a4*b5 + a5*b4 + a6*b3 + a7*b2 + a8*b1 + a9*b0 - s10 := c10 + a0*b10 + a1*b9 + a2*b8 + a3*b7 + a4*b6 + a5*b5 + a6*b4 + a7*b3 + a8*b2 + a9*b1 + a10*b0 - s11 := c11 + a0*b11 + a1*b10 + a2*b9 + a3*b8 + a4*b7 + a5*b6 + a6*b5 + a7*b4 + a8*b3 + a9*b2 + a10*b1 + a11*b0 - s12 := a1*b11 + a2*b10 + a3*b9 + a4*b8 + a5*b7 + a6*b6 + a7*b5 + a8*b4 + a9*b3 + a10*b2 + a11*b1 - s13 := a2*b11 + a3*b10 + a4*b9 + a5*b8 + a6*b7 + a7*b6 + a8*b5 + a9*b4 + a10*b3 + a11*b2 - s14 := a3*b11 + a4*b10 + a5*b9 + a6*b8 + a7*b7 + a8*b6 + a9*b5 + a10*b4 + a11*b3 - s15 := a4*b11 + a5*b10 + a6*b9 + a7*b8 + a8*b7 + a9*b6 + a10*b5 + a11*b4 - s16 := a5*b11 + a6*b10 + a7*b9 + a8*b8 + a9*b7 + a10*b6 + a11*b5 - s17 := a6*b11 + a7*b10 + a8*b9 + a9*b8 + a10*b7 + a11*b6 - s18 := a7*b11 + a8*b10 + a9*b9 + a10*b8 + a11*b7 - s19 := a8*b11 + a9*b10 + a10*b9 + a11*b8 - s20 := a9*b11 + a10*b10 + a11*b9 - s21 := a10*b11 + a11*b10 - s22 := a11 * b11 - s23 := int64(0) - - carry[0] = (s0 + (1 << 20)) >> 21 - s1 += carry[0] - s0 -= carry[0] << 21 - carry[2] = (s2 + (1 << 20)) >> 21 - s3 += carry[2] - s2 -= carry[2] << 21 - carry[4] = (s4 + (1 << 20)) >> 21 - s5 += carry[4] - s4 -= carry[4] << 21 - carry[6] = (s6 + (1 << 20)) >> 21 - s7 += carry[6] - s6 -= carry[6] << 21 - carry[8] = (s8 + (1 << 20)) >> 21 - s9 += carry[8] - s8 -= carry[8] << 21 - carry[10] = (s10 + (1 << 20)) >> 21 - s11 += carry[10] - s10 -= carry[10] << 21 - carry[12] = (s12 + (1 << 20)) >> 21 - s13 += carry[12] - s12 -= carry[12] << 21 - carry[14] = (s14 + (1 << 20)) >> 21 - s15 += carry[14] - s14 -= carry[14] << 21 - carry[16] = (s16 + (1 << 20)) >> 21 - s17 += carry[16] - s16 -= carry[16] << 21 - carry[18] = (s18 + (1 << 20)) >> 21 - s19 += carry[18] - s18 -= carry[18] << 21 - carry[20] = (s20 + (1 << 20)) >> 21 - s21 += carry[20] - s20 -= carry[20] << 21 - carry[22] = (s22 + (1 << 20)) >> 21 - s23 += carry[22] - s22 -= carry[22] << 21 - - carry[1] = (s1 + (1 << 20)) >> 21 - s2 += carry[1] - s1 -= carry[1] << 21 - carry[3] = (s3 + (1 << 20)) >> 21 - s4 += carry[3] - s3 -= carry[3] << 21 - carry[5] = (s5 + (1 << 20)) >> 21 - s6 += carry[5] - s5 -= carry[5] << 21 - carry[7] = (s7 + (1 << 20)) >> 21 - s8 += carry[7] - s7 -= carry[7] << 21 - carry[9] = (s9 + (1 << 20)) >> 21 - s10 += carry[9] - s9 -= carry[9] << 21 - carry[11] = (s11 + (1 << 20)) >> 21 - s12 += carry[11] - s11 -= carry[11] << 21 - carry[13] = (s13 + (1 << 20)) >> 21 - s14 += carry[13] - s13 -= carry[13] << 21 - carry[15] = (s15 + (1 << 20)) >> 21 - s16 += carry[15] - s15 -= carry[15] << 21 - carry[17] = (s17 + (1 << 20)) >> 21 - s18 += carry[17] - s17 -= carry[17] << 21 - carry[19] = (s19 + (1 << 20)) >> 21 - s20 += carry[19] - s19 -= carry[19] << 21 - carry[21] = (s21 + (1 << 20)) >> 21 - s22 += carry[21] - s21 -= carry[21] << 21 - - s11 += s23 * 666643 - s12 += s23 * 470296 - s13 += s23 * 654183 - s14 -= s23 * 997805 - s15 += s23 * 136657 - s16 -= s23 * 683901 - s23 = 0 - - s10 += s22 * 666643 - s11 += s22 * 470296 - s12 += s22 * 654183 - s13 -= s22 * 997805 - s14 += s22 * 136657 - s15 -= s22 * 683901 - s22 = 0 - - s9 += s21 * 666643 - s10 += s21 * 470296 - s11 += s21 * 654183 - s12 -= s21 * 997805 - s13 += s21 * 136657 - s14 -= s21 * 683901 - s21 = 0 - - s8 += s20 * 666643 - s9 += s20 * 470296 - s10 += s20 * 654183 - s11 -= s20 * 997805 - s12 += s20 * 136657 - s13 -= s20 * 683901 - s20 = 0 - - s7 += s19 * 666643 - s8 += s19 * 470296 - s9 += s19 * 654183 - s10 -= s19 * 997805 - s11 += s19 * 136657 - s12 -= s19 * 683901 - s19 = 0 - - s6 += s18 * 666643 - s7 += s18 * 470296 - s8 += s18 * 654183 - s9 -= s18 * 997805 - s10 += s18 * 136657 - s11 -= s18 * 683901 - s18 = 0 - - carry[6] = (s6 + (1 << 20)) >> 21 - s7 += carry[6] - s6 -= carry[6] << 21 - carry[8] = (s8 + (1 << 20)) >> 21 - s9 += carry[8] - s8 -= carry[8] << 21 - carry[10] = (s10 + (1 << 20)) >> 21 - s11 += carry[10] - s10 -= carry[10] << 21 - carry[12] = (s12 + (1 << 20)) >> 21 - s13 += carry[12] - s12 -= carry[12] << 21 - carry[14] = (s14 + (1 << 20)) >> 21 - s15 += carry[14] - s14 -= carry[14] << 21 - carry[16] = (s16 + (1 << 20)) >> 21 - s17 += carry[16] - s16 -= carry[16] << 21 - - carry[7] = (s7 + (1 << 20)) >> 21 - s8 += carry[7] - s7 -= carry[7] << 21 - carry[9] = (s9 + (1 << 20)) >> 21 - s10 += carry[9] - s9 -= carry[9] << 21 - carry[11] = (s11 + (1 << 20)) >> 21 - s12 += carry[11] - s11 -= carry[11] << 21 - carry[13] = (s13 + (1 << 20)) >> 21 - s14 += carry[13] - s13 -= carry[13] << 21 - carry[15] = (s15 + (1 << 20)) >> 21 - s16 += carry[15] - s15 -= carry[15] << 21 - - s5 += s17 * 666643 - s6 += s17 * 470296 - s7 += s17 * 654183 - s8 -= s17 * 997805 - s9 += s17 * 136657 - s10 -= s17 * 683901 - s17 = 0 - - s4 += s16 * 666643 - s5 += s16 * 470296 - s6 += s16 * 654183 - s7 -= s16 * 997805 - s8 += s16 * 136657 - s9 -= s16 * 683901 - s16 = 0 - - s3 += s15 * 666643 - s4 += s15 * 470296 - s5 += s15 * 654183 - s6 -= s15 * 997805 - s7 += s15 * 136657 - s8 -= s15 * 683901 - s15 = 0 - - s2 += s14 * 666643 - s3 += s14 * 470296 - s4 += s14 * 654183 - s5 -= s14 * 997805 - s6 += s14 * 136657 - s7 -= s14 * 683901 - s14 = 0 - - s1 += s13 * 666643 - s2 += s13 * 470296 - s3 += s13 * 654183 - s4 -= s13 * 997805 - s5 += s13 * 136657 - s6 -= s13 * 683901 - s13 = 0 - - s0 += s12 * 666643 - s1 += s12 * 470296 - s2 += s12 * 654183 - s3 -= s12 * 997805 - s4 += s12 * 136657 - s5 -= s12 * 683901 - s12 = 0 - - carry[0] = (s0 + (1 << 20)) >> 21 - s1 += carry[0] - s0 -= carry[0] << 21 - carry[2] = (s2 + (1 << 20)) >> 21 - s3 += carry[2] - s2 -= carry[2] << 21 - carry[4] = (s4 + (1 << 20)) >> 21 - s5 += carry[4] - s4 -= carry[4] << 21 - carry[6] = (s6 + (1 << 20)) >> 21 - s7 += carry[6] - s6 -= carry[6] << 21 - carry[8] = (s8 + (1 << 20)) >> 21 - s9 += carry[8] - s8 -= carry[8] << 21 - carry[10] = (s10 + (1 << 20)) >> 21 - s11 += carry[10] - s10 -= carry[10] << 21 - - carry[1] = (s1 + (1 << 20)) >> 21 - s2 += carry[1] - s1 -= carry[1] << 21 - carry[3] = (s3 + (1 << 20)) >> 21 - s4 += carry[3] - s3 -= carry[3] << 21 - carry[5] = (s5 + (1 << 20)) >> 21 - s6 += carry[5] - s5 -= carry[5] << 21 - carry[7] = (s7 + (1 << 20)) >> 21 - s8 += carry[7] - s7 -= carry[7] << 21 - carry[9] = (s9 + (1 << 20)) >> 21 - s10 += carry[9] - s9 -= carry[9] << 21 - carry[11] = (s11 + (1 << 20)) >> 21 - s12 += carry[11] - s11 -= carry[11] << 21 - - s0 += s12 * 666643 - s1 += s12 * 470296 - s2 += s12 * 654183 - s3 -= s12 * 997805 - s4 += s12 * 136657 - s5 -= s12 * 683901 - s12 = 0 - - carry[0] = s0 >> 21 - s1 += carry[0] - s0 -= carry[0] << 21 - carry[1] = s1 >> 21 - s2 += carry[1] - s1 -= carry[1] << 21 - carry[2] = s2 >> 21 - s3 += carry[2] - s2 -= carry[2] << 21 - carry[3] = s3 >> 21 - s4 += carry[3] - s3 -= carry[3] << 21 - carry[4] = s4 >> 21 - s5 += carry[4] - s4 -= carry[4] << 21 - carry[5] = s5 >> 21 - s6 += carry[5] - s5 -= carry[5] << 21 - carry[6] = s6 >> 21 - s7 += carry[6] - s6 -= carry[6] << 21 - carry[7] = s7 >> 21 - s8 += carry[7] - s7 -= carry[7] << 21 - carry[8] = s8 >> 21 - s9 += carry[8] - s8 -= carry[8] << 21 - carry[9] = s9 >> 21 - s10 += carry[9] - s9 -= carry[9] << 21 - carry[10] = s10 >> 21 - s11 += carry[10] - s10 -= carry[10] << 21 - carry[11] = s11 >> 21 - s12 += carry[11] - s11 -= carry[11] << 21 - - s0 += s12 * 666643 - s1 += s12 * 470296 - s2 += s12 * 654183 - s3 -= s12 * 997805 - s4 += s12 * 136657 - s5 -= s12 * 683901 - s12 = 0 - - carry[0] = s0 >> 21 - s1 += carry[0] - s0 -= carry[0] << 21 - carry[1] = s1 >> 21 - s2 += carry[1] - s1 -= carry[1] << 21 - carry[2] = s2 >> 21 - s3 += carry[2] - s2 -= carry[2] << 21 - carry[3] = s3 >> 21 - s4 += carry[3] - s3 -= carry[3] << 21 - carry[4] = s4 >> 21 - s5 += carry[4] - s4 -= carry[4] << 21 - carry[5] = s5 >> 21 - s6 += carry[5] - s5 -= carry[5] << 21 - carry[6] = s6 >> 21 - s7 += carry[6] - s6 -= carry[6] << 21 - carry[7] = s7 >> 21 - s8 += carry[7] - s7 -= carry[7] << 21 - carry[8] = s8 >> 21 - s9 += carry[8] - s8 -= carry[8] << 21 - carry[9] = s9 >> 21 - s10 += carry[9] - s9 -= carry[9] << 21 - carry[10] = s10 >> 21 - s11 += carry[10] - s10 -= carry[10] << 21 - - s[0] = byte(s0 >> 0) - s[1] = byte(s0 >> 8) - s[2] = byte((s0 >> 16) | (s1 << 5)) - s[3] = byte(s1 >> 3) - s[4] = byte(s1 >> 11) - s[5] = byte((s1 >> 19) | (s2 << 2)) - s[6] = byte(s2 >> 6) - s[7] = byte((s2 >> 14) | (s3 << 7)) - s[8] = byte(s3 >> 1) - s[9] = byte(s3 >> 9) - s[10] = byte((s3 >> 17) | (s4 << 4)) - s[11] = byte(s4 >> 4) - s[12] = byte(s4 >> 12) - s[13] = byte((s4 >> 20) | (s5 << 1)) - s[14] = byte(s5 >> 7) - s[15] = byte((s5 >> 15) | (s6 << 6)) - s[16] = byte(s6 >> 2) - s[17] = byte(s6 >> 10) - s[18] = byte((s6 >> 18) | (s7 << 3)) - s[19] = byte(s7 >> 5) - s[20] = byte(s7 >> 13) - s[21] = byte(s8 >> 0) - s[22] = byte(s8 >> 8) - s[23] = byte((s8 >> 16) | (s9 << 5)) - s[24] = byte(s9 >> 3) - s[25] = byte(s9 >> 11) - s[26] = byte((s9 >> 19) | (s10 << 2)) - s[27] = byte(s10 >> 6) - s[28] = byte((s10 >> 14) | (s11 << 7)) - s[29] = byte(s11 >> 1) - s[30] = byte(s11 >> 9) - s[31] = byte(s11 >> 17) -} - -// Input: -// s[0]+256*s[1]+...+256^63*s[63] = s -// -// Output: -// s[0]+256*s[1]+...+256^31*s[31] = s mod l -// where l = 2^252 + 27742317777372353535851937790883648493. -func ScReduce(out *[32]byte, s *[64]byte) { - s0 := 2097151 & load3(s[:]) - s1 := 2097151 & (load4(s[2:]) >> 5) - s2 := 2097151 & (load3(s[5:]) >> 2) - s3 := 2097151 & (load4(s[7:]) >> 7) - s4 := 2097151 & (load4(s[10:]) >> 4) - s5 := 2097151 & (load3(s[13:]) >> 1) - s6 := 2097151 & (load4(s[15:]) >> 6) - s7 := 2097151 & (load3(s[18:]) >> 3) - s8 := 2097151 & load3(s[21:]) - s9 := 2097151 & (load4(s[23:]) >> 5) - s10 := 2097151 & (load3(s[26:]) >> 2) - s11 := 2097151 & (load4(s[28:]) >> 7) - s12 := 2097151 & (load4(s[31:]) >> 4) - s13 := 2097151 & (load3(s[34:]) >> 1) - s14 := 2097151 & (load4(s[36:]) >> 6) - s15 := 2097151 & (load3(s[39:]) >> 3) - s16 := 2097151 & load3(s[42:]) - s17 := 2097151 & (load4(s[44:]) >> 5) - s18 := 2097151 & (load3(s[47:]) >> 2) - s19 := 2097151 & (load4(s[49:]) >> 7) - s20 := 2097151 & (load4(s[52:]) >> 4) - s21 := 2097151 & (load3(s[55:]) >> 1) - s22 := 2097151 & (load4(s[57:]) >> 6) - s23 := (load4(s[60:]) >> 3) - - s11 += s23 * 666643 - s12 += s23 * 470296 - s13 += s23 * 654183 - s14 -= s23 * 997805 - s15 += s23 * 136657 - s16 -= s23 * 683901 - s23 = 0 - - s10 += s22 * 666643 - s11 += s22 * 470296 - s12 += s22 * 654183 - s13 -= s22 * 997805 - s14 += s22 * 136657 - s15 -= s22 * 683901 - s22 = 0 - - s9 += s21 * 666643 - s10 += s21 * 470296 - s11 += s21 * 654183 - s12 -= s21 * 997805 - s13 += s21 * 136657 - s14 -= s21 * 683901 - s21 = 0 - - s8 += s20 * 666643 - s9 += s20 * 470296 - s10 += s20 * 654183 - s11 -= s20 * 997805 - s12 += s20 * 136657 - s13 -= s20 * 683901 - s20 = 0 - - s7 += s19 * 666643 - s8 += s19 * 470296 - s9 += s19 * 654183 - s10 -= s19 * 997805 - s11 += s19 * 136657 - s12 -= s19 * 683901 - s19 = 0 - - s6 += s18 * 666643 - s7 += s18 * 470296 - s8 += s18 * 654183 - s9 -= s18 * 997805 - s10 += s18 * 136657 - s11 -= s18 * 683901 - s18 = 0 - - var carry [17]int64 - - carry[6] = (s6 + (1 << 20)) >> 21 - s7 += carry[6] - s6 -= carry[6] << 21 - carry[8] = (s8 + (1 << 20)) >> 21 - s9 += carry[8] - s8 -= carry[8] << 21 - carry[10] = (s10 + (1 << 20)) >> 21 - s11 += carry[10] - s10 -= carry[10] << 21 - carry[12] = (s12 + (1 << 20)) >> 21 - s13 += carry[12] - s12 -= carry[12] << 21 - carry[14] = (s14 + (1 << 20)) >> 21 - s15 += carry[14] - s14 -= carry[14] << 21 - carry[16] = (s16 + (1 << 20)) >> 21 - s17 += carry[16] - s16 -= carry[16] << 21 - - carry[7] = (s7 + (1 << 20)) >> 21 - s8 += carry[7] - s7 -= carry[7] << 21 - carry[9] = (s9 + (1 << 20)) >> 21 - s10 += carry[9] - s9 -= carry[9] << 21 - carry[11] = (s11 + (1 << 20)) >> 21 - s12 += carry[11] - s11 -= carry[11] << 21 - carry[13] = (s13 + (1 << 20)) >> 21 - s14 += carry[13] - s13 -= carry[13] << 21 - carry[15] = (s15 + (1 << 20)) >> 21 - s16 += carry[15] - s15 -= carry[15] << 21 - - s5 += s17 * 666643 - s6 += s17 * 470296 - s7 += s17 * 654183 - s8 -= s17 * 997805 - s9 += s17 * 136657 - s10 -= s17 * 683901 - s17 = 0 - - s4 += s16 * 666643 - s5 += s16 * 470296 - s6 += s16 * 654183 - s7 -= s16 * 997805 - s8 += s16 * 136657 - s9 -= s16 * 683901 - s16 = 0 - - s3 += s15 * 666643 - s4 += s15 * 470296 - s5 += s15 * 654183 - s6 -= s15 * 997805 - s7 += s15 * 136657 - s8 -= s15 * 683901 - s15 = 0 - - s2 += s14 * 666643 - s3 += s14 * 470296 - s4 += s14 * 654183 - s5 -= s14 * 997805 - s6 += s14 * 136657 - s7 -= s14 * 683901 - s14 = 0 - - s1 += s13 * 666643 - s2 += s13 * 470296 - s3 += s13 * 654183 - s4 -= s13 * 997805 - s5 += s13 * 136657 - s6 -= s13 * 683901 - s13 = 0 - - s0 += s12 * 666643 - s1 += s12 * 470296 - s2 += s12 * 654183 - s3 -= s12 * 997805 - s4 += s12 * 136657 - s5 -= s12 * 683901 - s12 = 0 - - carry[0] = (s0 + (1 << 20)) >> 21 - s1 += carry[0] - s0 -= carry[0] << 21 - carry[2] = (s2 + (1 << 20)) >> 21 - s3 += carry[2] - s2 -= carry[2] << 21 - carry[4] = (s4 + (1 << 20)) >> 21 - s5 += carry[4] - s4 -= carry[4] << 21 - carry[6] = (s6 + (1 << 20)) >> 21 - s7 += carry[6] - s6 -= carry[6] << 21 - carry[8] = (s8 + (1 << 20)) >> 21 - s9 += carry[8] - s8 -= carry[8] << 21 - carry[10] = (s10 + (1 << 20)) >> 21 - s11 += carry[10] - s10 -= carry[10] << 21 - - carry[1] = (s1 + (1 << 20)) >> 21 - s2 += carry[1] - s1 -= carry[1] << 21 - carry[3] = (s3 + (1 << 20)) >> 21 - s4 += carry[3] - s3 -= carry[3] << 21 - carry[5] = (s5 + (1 << 20)) >> 21 - s6 += carry[5] - s5 -= carry[5] << 21 - carry[7] = (s7 + (1 << 20)) >> 21 - s8 += carry[7] - s7 -= carry[7] << 21 - carry[9] = (s9 + (1 << 20)) >> 21 - s10 += carry[9] - s9 -= carry[9] << 21 - carry[11] = (s11 + (1 << 20)) >> 21 - s12 += carry[11] - s11 -= carry[11] << 21 - - s0 += s12 * 666643 - s1 += s12 * 470296 - s2 += s12 * 654183 - s3 -= s12 * 997805 - s4 += s12 * 136657 - s5 -= s12 * 683901 - s12 = 0 - - carry[0] = s0 >> 21 - s1 += carry[0] - s0 -= carry[0] << 21 - carry[1] = s1 >> 21 - s2 += carry[1] - s1 -= carry[1] << 21 - carry[2] = s2 >> 21 - s3 += carry[2] - s2 -= carry[2] << 21 - carry[3] = s3 >> 21 - s4 += carry[3] - s3 -= carry[3] << 21 - carry[4] = s4 >> 21 - s5 += carry[4] - s4 -= carry[4] << 21 - carry[5] = s5 >> 21 - s6 += carry[5] - s5 -= carry[5] << 21 - carry[6] = s6 >> 21 - s7 += carry[6] - s6 -= carry[6] << 21 - carry[7] = s7 >> 21 - s8 += carry[7] - s7 -= carry[7] << 21 - carry[8] = s8 >> 21 - s9 += carry[8] - s8 -= carry[8] << 21 - carry[9] = s9 >> 21 - s10 += carry[9] - s9 -= carry[9] << 21 - carry[10] = s10 >> 21 - s11 += carry[10] - s10 -= carry[10] << 21 - carry[11] = s11 >> 21 - s12 += carry[11] - s11 -= carry[11] << 21 - - s0 += s12 * 666643 - s1 += s12 * 470296 - s2 += s12 * 654183 - s3 -= s12 * 997805 - s4 += s12 * 136657 - s5 -= s12 * 683901 - s12 = 0 - - carry[0] = s0 >> 21 - s1 += carry[0] - s0 -= carry[0] << 21 - carry[1] = s1 >> 21 - s2 += carry[1] - s1 -= carry[1] << 21 - carry[2] = s2 >> 21 - s3 += carry[2] - s2 -= carry[2] << 21 - carry[3] = s3 >> 21 - s4 += carry[3] - s3 -= carry[3] << 21 - carry[4] = s4 >> 21 - s5 += carry[4] - s4 -= carry[4] << 21 - carry[5] = s5 >> 21 - s6 += carry[5] - s5 -= carry[5] << 21 - carry[6] = s6 >> 21 - s7 += carry[6] - s6 -= carry[6] << 21 - carry[7] = s7 >> 21 - s8 += carry[7] - s7 -= carry[7] << 21 - carry[8] = s8 >> 21 - s9 += carry[8] - s8 -= carry[8] << 21 - carry[9] = s9 >> 21 - s10 += carry[9] - s9 -= carry[9] << 21 - carry[10] = s10 >> 21 - s11 += carry[10] - s10 -= carry[10] << 21 - - out[0] = byte(s0 >> 0) - out[1] = byte(s0 >> 8) - out[2] = byte((s0 >> 16) | (s1 << 5)) - out[3] = byte(s1 >> 3) - out[4] = byte(s1 >> 11) - out[5] = byte((s1 >> 19) | (s2 << 2)) - out[6] = byte(s2 >> 6) - out[7] = byte((s2 >> 14) | (s3 << 7)) - out[8] = byte(s3 >> 1) - out[9] = byte(s3 >> 9) - out[10] = byte((s3 >> 17) | (s4 << 4)) - out[11] = byte(s4 >> 4) - out[12] = byte(s4 >> 12) - out[13] = byte((s4 >> 20) | (s5 << 1)) - out[14] = byte(s5 >> 7) - out[15] = byte((s5 >> 15) | (s6 << 6)) - out[16] = byte(s6 >> 2) - out[17] = byte(s6 >> 10) - out[18] = byte((s6 >> 18) | (s7 << 3)) - out[19] = byte(s7 >> 5) - out[20] = byte(s7 >> 13) - out[21] = byte(s8 >> 0) - out[22] = byte(s8 >> 8) - out[23] = byte((s8 >> 16) | (s9 << 5)) - out[24] = byte(s9 >> 3) - out[25] = byte(s9 >> 11) - out[26] = byte((s9 >> 19) | (s10 << 2)) - out[27] = byte(s10 >> 6) - out[28] = byte((s10 >> 14) | (s11 << 7)) - out[29] = byte(s11 >> 1) - out[30] = byte(s11 >> 9) - out[31] = byte(s11 >> 17) -} diff --git a/vendor/golang.org/x/crypto/ssh/buffer.go b/vendor/golang.org/x/crypto/ssh/buffer.go deleted file mode 100644 index 6931b51..0000000 --- a/vendor/golang.org/x/crypto/ssh/buffer.go +++ /dev/null @@ -1,98 +0,0 @@ -// Copyright 2012 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 ssh - -import ( - "io" - "sync" -) - -// buffer provides a linked list buffer for data exchange -// between producer and consumer. Theoretically the buffer is -// of unlimited capacity as it does no allocation of its own. -type buffer struct { - // protects concurrent access to head, tail and closed - *sync.Cond - - head *element // the buffer that will be read first - tail *element // the buffer that will be read last - - closed bool -} - -// An element represents a single link in a linked list. -type element struct { - buf []byte - next *element -} - -// newBuffer returns an empty buffer that is not closed. -func newBuffer() *buffer { - e := new(element) - b := &buffer{ - Cond: newCond(), - head: e, - tail: e, - } - return b -} - -// write makes buf available for Read to receive. -// buf must not be modified after the call to write. -func (b *buffer) write(buf []byte) { - b.Cond.L.Lock() - e := &element{buf: buf} - b.tail.next = e - b.tail = e - b.Cond.Signal() - b.Cond.L.Unlock() -} - -// eof closes the buffer. Reads from the buffer once all -// the data has been consumed will receive os.EOF. -func (b *buffer) eof() error { - b.Cond.L.Lock() - b.closed = true - b.Cond.Signal() - b.Cond.L.Unlock() - return nil -} - -// Read reads data from the internal buffer in buf. Reads will block -// if no data is available, or until the buffer is closed. -func (b *buffer) Read(buf []byte) (n int, err error) { - b.Cond.L.Lock() - defer b.Cond.L.Unlock() - - for len(buf) > 0 { - // if there is data in b.head, copy it - if len(b.head.buf) > 0 { - r := copy(buf, b.head.buf) - buf, b.head.buf = buf[r:], b.head.buf[r:] - n += r - continue - } - // if there is a next buffer, make it the head - if len(b.head.buf) == 0 && b.head != b.tail { - b.head = b.head.next - continue - } - - // if at least one byte has been copied, return - if n > 0 { - break - } - - // if nothing was read, and there is nothing outstanding - // check to see if the buffer is closed. - if b.closed { - err = io.EOF - break - } - // out of buffers, wait for producer - b.Cond.Wait() - } - return -} diff --git a/vendor/golang.org/x/crypto/ssh/certs.go b/vendor/golang.org/x/crypto/ssh/certs.go deleted file mode 100644 index 6331c94..0000000 --- a/vendor/golang.org/x/crypto/ssh/certs.go +++ /dev/null @@ -1,503 +0,0 @@ -// Copyright 2012 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 ssh - -import ( - "bytes" - "errors" - "fmt" - "io" - "net" - "sort" - "time" -) - -// These constants from [PROTOCOL.certkeys] represent the algorithm names -// for certificate types supported by this package. -const ( - CertAlgoRSAv01 = "ssh-rsa-cert-v01@openssh.com" - CertAlgoDSAv01 = "ssh-dss-cert-v01@openssh.com" - CertAlgoECDSA256v01 = "ecdsa-sha2-nistp256-cert-v01@openssh.com" - CertAlgoECDSA384v01 = "ecdsa-sha2-nistp384-cert-v01@openssh.com" - CertAlgoECDSA521v01 = "ecdsa-sha2-nistp521-cert-v01@openssh.com" - CertAlgoED25519v01 = "ssh-ed25519-cert-v01@openssh.com" -) - -// Certificate types distinguish between host and user -// certificates. The values can be set in the CertType field of -// Certificate. -const ( - UserCert = 1 - HostCert = 2 -) - -// Signature represents a cryptographic signature. -type Signature struct { - Format string - Blob []byte -} - -// CertTimeInfinity can be used for OpenSSHCertV01.ValidBefore to indicate that -// a certificate does not expire. -const CertTimeInfinity = 1<<64 - 1 - -// An Certificate represents an OpenSSH certificate as defined in -// [PROTOCOL.certkeys]?rev=1.8. -type Certificate struct { - Nonce []byte - Key PublicKey - Serial uint64 - CertType uint32 - KeyId string - ValidPrincipals []string - ValidAfter uint64 - ValidBefore uint64 - Permissions - Reserved []byte - SignatureKey PublicKey - Signature *Signature -} - -// genericCertData holds the key-independent part of the certificate data. -// Overall, certificates contain an nonce, public key fields and -// key-independent fields. -type genericCertData struct { - Serial uint64 - CertType uint32 - KeyId string - ValidPrincipals []byte - ValidAfter uint64 - ValidBefore uint64 - CriticalOptions []byte - Extensions []byte - Reserved []byte - SignatureKey []byte - Signature []byte -} - -func marshalStringList(namelist []string) []byte { - var to []byte - for _, name := range namelist { - s := struct{ N string }{name} - to = append(to, Marshal(&s)...) - } - return to -} - -type optionsTuple struct { - Key string - Value []byte -} - -type optionsTupleValue struct { - Value string -} - -// serialize a map of critical options or extensions -// issue #10569 - per [PROTOCOL.certkeys] and SSH implementation, -// we need two length prefixes for a non-empty string value -func marshalTuples(tups map[string]string) []byte { - keys := make([]string, 0, len(tups)) - for key := range tups { - keys = append(keys, key) - } - sort.Strings(keys) - - var ret []byte - for _, key := range keys { - s := optionsTuple{Key: key} - if value := tups[key]; len(value) > 0 { - s.Value = Marshal(&optionsTupleValue{value}) - } - ret = append(ret, Marshal(&s)...) - } - return ret -} - -// issue #10569 - per [PROTOCOL.certkeys] and SSH implementation, -// we need two length prefixes for a non-empty option value -func parseTuples(in []byte) (map[string]string, error) { - tups := map[string]string{} - var lastKey string - var haveLastKey bool - - for len(in) > 0 { - var key, val, extra []byte - var ok bool - - if key, in, ok = parseString(in); !ok { - return nil, errShortRead - } - keyStr := string(key) - // according to [PROTOCOL.certkeys], the names must be in - // lexical order. - if haveLastKey && keyStr <= lastKey { - return nil, fmt.Errorf("ssh: certificate options are not in lexical order") - } - lastKey, haveLastKey = keyStr, true - // the next field is a data field, which if non-empty has a string embedded - if val, in, ok = parseString(in); !ok { - return nil, errShortRead - } - if len(val) > 0 { - val, extra, ok = parseString(val) - if !ok { - return nil, errShortRead - } - if len(extra) > 0 { - return nil, fmt.Errorf("ssh: unexpected trailing data after certificate option value") - } - tups[keyStr] = string(val) - } else { - tups[keyStr] = "" - } - } - return tups, nil -} - -func parseCert(in []byte, privAlgo string) (*Certificate, error) { - nonce, rest, ok := parseString(in) - if !ok { - return nil, errShortRead - } - - key, rest, err := parsePubKey(rest, privAlgo) - if err != nil { - return nil, err - } - - var g genericCertData - if err := Unmarshal(rest, &g); err != nil { - return nil, err - } - - c := &Certificate{ - Nonce: nonce, - Key: key, - Serial: g.Serial, - CertType: g.CertType, - KeyId: g.KeyId, - ValidAfter: g.ValidAfter, - ValidBefore: g.ValidBefore, - } - - for principals := g.ValidPrincipals; len(principals) > 0; { - principal, rest, ok := parseString(principals) - if !ok { - return nil, errShortRead - } - c.ValidPrincipals = append(c.ValidPrincipals, string(principal)) - principals = rest - } - - c.CriticalOptions, err = parseTuples(g.CriticalOptions) - if err != nil { - return nil, err - } - c.Extensions, err = parseTuples(g.Extensions) - if err != nil { - return nil, err - } - c.Reserved = g.Reserved - k, err := ParsePublicKey(g.SignatureKey) - if err != nil { - return nil, err - } - - c.SignatureKey = k - c.Signature, rest, ok = parseSignatureBody(g.Signature) - if !ok || len(rest) > 0 { - return nil, errors.New("ssh: signature parse error") - } - - return c, nil -} - -type openSSHCertSigner struct { - pub *Certificate - signer Signer -} - -// NewCertSigner returns a Signer that signs with the given Certificate, whose -// private key is held by signer. It returns an error if the public key in cert -// doesn't match the key used by signer. -func NewCertSigner(cert *Certificate, signer Signer) (Signer, error) { - if bytes.Compare(cert.Key.Marshal(), signer.PublicKey().Marshal()) != 0 { - return nil, errors.New("ssh: signer and cert have different public key") - } - - return &openSSHCertSigner{cert, signer}, nil -} - -func (s *openSSHCertSigner) Sign(rand io.Reader, data []byte) (*Signature, error) { - return s.signer.Sign(rand, data) -} - -func (s *openSSHCertSigner) PublicKey() PublicKey { - return s.pub -} - -const sourceAddressCriticalOption = "source-address" - -// CertChecker does the work of verifying a certificate. Its methods -// can be plugged into ClientConfig.HostKeyCallback and -// ServerConfig.PublicKeyCallback. For the CertChecker to work, -// minimally, the IsAuthority callback should be set. -type CertChecker struct { - // SupportedCriticalOptions lists the CriticalOptions that the - // server application layer understands. These are only used - // for user certificates. - SupportedCriticalOptions []string - - // IsAuthority should return true if the key is recognized as - // an authority. This allows for certificates to be signed by other - // certificates. - IsAuthority func(auth PublicKey) bool - - // Clock is used for verifying time stamps. If nil, time.Now - // is used. - Clock func() time.Time - - // UserKeyFallback is called when CertChecker.Authenticate encounters a - // public key that is not a certificate. It must implement validation - // of user keys or else, if nil, all such keys are rejected. - UserKeyFallback func(conn ConnMetadata, key PublicKey) (*Permissions, error) - - // HostKeyFallback is called when CertChecker.CheckHostKey encounters a - // public key that is not a certificate. It must implement host key - // validation or else, if nil, all such keys are rejected. - HostKeyFallback func(addr string, remote net.Addr, key PublicKey) error - - // IsRevoked is called for each certificate so that revocation checking - // can be implemented. It should return true if the given certificate - // is revoked and false otherwise. If nil, no certificates are - // considered to have been revoked. - IsRevoked func(cert *Certificate) bool -} - -// CheckHostKey checks a host key certificate. This method can be -// plugged into ClientConfig.HostKeyCallback. -func (c *CertChecker) CheckHostKey(addr string, remote net.Addr, key PublicKey) error { - cert, ok := key.(*Certificate) - if !ok { - if c.HostKeyFallback != nil { - return c.HostKeyFallback(addr, remote, key) - } - return errors.New("ssh: non-certificate host key") - } - if cert.CertType != HostCert { - return fmt.Errorf("ssh: certificate presented as a host key has type %d", cert.CertType) - } - - return c.CheckCert(addr, cert) -} - -// Authenticate checks a user certificate. Authenticate can be used as -// a value for ServerConfig.PublicKeyCallback. -func (c *CertChecker) Authenticate(conn ConnMetadata, pubKey PublicKey) (*Permissions, error) { - cert, ok := pubKey.(*Certificate) - if !ok { - if c.UserKeyFallback != nil { - return c.UserKeyFallback(conn, pubKey) - } - return nil, errors.New("ssh: normal key pairs not accepted") - } - - if cert.CertType != UserCert { - return nil, fmt.Errorf("ssh: cert has type %d", cert.CertType) - } - - if err := c.CheckCert(conn.User(), cert); err != nil { - return nil, err - } - - return &cert.Permissions, nil -} - -// CheckCert checks CriticalOptions, ValidPrincipals, revocation, timestamp and -// the signature of the certificate. -func (c *CertChecker) CheckCert(principal string, cert *Certificate) error { - if c.IsRevoked != nil && c.IsRevoked(cert) { - return fmt.Errorf("ssh: certicate serial %d revoked", cert.Serial) - } - - for opt, _ := range cert.CriticalOptions { - // sourceAddressCriticalOption will be enforced by - // serverAuthenticate - if opt == sourceAddressCriticalOption { - continue - } - - found := false - for _, supp := range c.SupportedCriticalOptions { - if supp == opt { - found = true - break - } - } - if !found { - return fmt.Errorf("ssh: unsupported critical option %q in certificate", opt) - } - } - - if len(cert.ValidPrincipals) > 0 { - // By default, certs are valid for all users/hosts. - found := false - for _, p := range cert.ValidPrincipals { - if p == principal { - found = true - break - } - } - if !found { - return fmt.Errorf("ssh: principal %q not in the set of valid principals for given certificate: %q", principal, cert.ValidPrincipals) - } - } - - if !c.IsAuthority(cert.SignatureKey) { - return fmt.Errorf("ssh: certificate signed by unrecognized authority") - } - - clock := c.Clock - if clock == nil { - clock = time.Now - } - - unixNow := clock().Unix() - if after := int64(cert.ValidAfter); after < 0 || unixNow < int64(cert.ValidAfter) { - return fmt.Errorf("ssh: cert is not yet valid") - } - if before := int64(cert.ValidBefore); cert.ValidBefore != uint64(CertTimeInfinity) && (unixNow >= before || before < 0) { - return fmt.Errorf("ssh: cert has expired") - } - if err := cert.SignatureKey.Verify(cert.bytesForSigning(), cert.Signature); err != nil { - return fmt.Errorf("ssh: certificate signature does not verify") - } - - return nil -} - -// SignCert sets c.SignatureKey to the authority's public key and stores a -// Signature, by authority, in the certificate. -func (c *Certificate) SignCert(rand io.Reader, authority Signer) error { - c.Nonce = make([]byte, 32) - if _, err := io.ReadFull(rand, c.Nonce); err != nil { - return err - } - c.SignatureKey = authority.PublicKey() - - sig, err := authority.Sign(rand, c.bytesForSigning()) - if err != nil { - return err - } - c.Signature = sig - return nil -} - -var certAlgoNames = map[string]string{ - KeyAlgoRSA: CertAlgoRSAv01, - KeyAlgoDSA: CertAlgoDSAv01, - KeyAlgoECDSA256: CertAlgoECDSA256v01, - KeyAlgoECDSA384: CertAlgoECDSA384v01, - KeyAlgoECDSA521: CertAlgoECDSA521v01, - KeyAlgoED25519: CertAlgoED25519v01, -} - -// certToPrivAlgo returns the underlying algorithm for a certificate algorithm. -// Panics if a non-certificate algorithm is passed. -func certToPrivAlgo(algo string) string { - for privAlgo, pubAlgo := range certAlgoNames { - if pubAlgo == algo { - return privAlgo - } - } - panic("unknown cert algorithm") -} - -func (cert *Certificate) bytesForSigning() []byte { - c2 := *cert - c2.Signature = nil - out := c2.Marshal() - // Drop trailing signature length. - return out[:len(out)-4] -} - -// Marshal serializes c into OpenSSH's wire format. It is part of the -// PublicKey interface. -func (c *Certificate) Marshal() []byte { - generic := genericCertData{ - Serial: c.Serial, - CertType: c.CertType, - KeyId: c.KeyId, - ValidPrincipals: marshalStringList(c.ValidPrincipals), - ValidAfter: uint64(c.ValidAfter), - ValidBefore: uint64(c.ValidBefore), - CriticalOptions: marshalTuples(c.CriticalOptions), - Extensions: marshalTuples(c.Extensions), - Reserved: c.Reserved, - SignatureKey: c.SignatureKey.Marshal(), - } - if c.Signature != nil { - generic.Signature = Marshal(c.Signature) - } - genericBytes := Marshal(&generic) - keyBytes := c.Key.Marshal() - _, keyBytes, _ = parseString(keyBytes) - prefix := Marshal(&struct { - Name string - Nonce []byte - Key []byte `ssh:"rest"` - }{c.Type(), c.Nonce, keyBytes}) - - result := make([]byte, 0, len(prefix)+len(genericBytes)) - result = append(result, prefix...) - result = append(result, genericBytes...) - return result -} - -// Type returns the key name. It is part of the PublicKey interface. -func (c *Certificate) Type() string { - algo, ok := certAlgoNames[c.Key.Type()] - if !ok { - panic("unknown cert key type " + c.Key.Type()) - } - return algo -} - -// Verify verifies a signature against the certificate's public -// key. It is part of the PublicKey interface. -func (c *Certificate) Verify(data []byte, sig *Signature) error { - return c.Key.Verify(data, sig) -} - -func parseSignatureBody(in []byte) (out *Signature, rest []byte, ok bool) { - format, in, ok := parseString(in) - if !ok { - return - } - - out = &Signature{ - Format: string(format), - } - - if out.Blob, in, ok = parseString(in); !ok { - return - } - - return out, in, ok -} - -func parseSignature(in []byte) (out *Signature, rest []byte, ok bool) { - sigBytes, rest, ok := parseString(in) - if !ok { - return - } - - out, trailing, ok := parseSignatureBody(sigBytes) - if !ok || len(trailing) > 0 { - return nil, nil, false - } - return -} diff --git a/vendor/golang.org/x/crypto/ssh/channel.go b/vendor/golang.org/x/crypto/ssh/channel.go deleted file mode 100644 index 6d709b5..0000000 --- a/vendor/golang.org/x/crypto/ssh/channel.go +++ /dev/null @@ -1,633 +0,0 @@ -// Copyright 2011 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 ssh - -import ( - "encoding/binary" - "errors" - "fmt" - "io" - "log" - "sync" -) - -const ( - minPacketLength = 9 - // channelMaxPacket contains the maximum number of bytes that will be - // sent in a single packet. As per RFC 4253, section 6.1, 32k is also - // the minimum. - channelMaxPacket = 1 << 15 - // We follow OpenSSH here. - channelWindowSize = 64 * channelMaxPacket -) - -// NewChannel represents an incoming request to a channel. It must either be -// accepted for use by calling Accept, or rejected by calling Reject. -type NewChannel interface { - // Accept accepts the channel creation request. It returns the Channel - // and a Go channel containing SSH requests. The Go channel must be - // serviced otherwise the Channel will hang. - Accept() (Channel, <-chan *Request, error) - - // Reject rejects the channel creation request. After calling - // this, no other methods on the Channel may be called. - Reject(reason RejectionReason, message string) error - - // ChannelType returns the type of the channel, as supplied by the - // client. - ChannelType() string - - // ExtraData returns the arbitrary payload for this channel, as supplied - // by the client. This data is specific to the channel type. - ExtraData() []byte -} - -// A Channel is an ordered, reliable, flow-controlled, duplex stream -// that is multiplexed over an SSH connection. -type Channel interface { - // Read reads up to len(data) bytes from the channel. - Read(data []byte) (int, error) - - // Write writes len(data) bytes to the channel. - Write(data []byte) (int, error) - - // Close signals end of channel use. No data may be sent after this - // call. - Close() error - - // CloseWrite signals the end of sending in-band - // data. Requests may still be sent, and the other side may - // still send data - CloseWrite() error - - // SendRequest sends a channel request. If wantReply is true, - // it will wait for a reply and return the result as a - // boolean, otherwise the return value will be false. Channel - // requests are out-of-band messages so they may be sent even - // if the data stream is closed or blocked by flow control. - // If the channel is closed before a reply is returned, io.EOF - // is returned. - SendRequest(name string, wantReply bool, payload []byte) (bool, error) - - // Stderr returns an io.ReadWriter that writes to this channel - // with the extended data type set to stderr. Stderr may - // safely be read and written from a different goroutine than - // Read and Write respectively. - Stderr() io.ReadWriter -} - -// Request is a request sent outside of the normal stream of -// data. Requests can either be specific to an SSH channel, or they -// can be global. -type Request struct { - Type string - WantReply bool - Payload []byte - - ch *channel - mux *mux -} - -// Reply sends a response to a request. It must be called for all requests -// where WantReply is true and is a no-op otherwise. The payload argument is -// ignored for replies to channel-specific requests. -func (r *Request) Reply(ok bool, payload []byte) error { - if !r.WantReply { - return nil - } - - if r.ch == nil { - return r.mux.ackRequest(ok, payload) - } - - return r.ch.ackRequest(ok) -} - -// RejectionReason is an enumeration used when rejecting channel creation -// requests. See RFC 4254, section 5.1. -type RejectionReason uint32 - -const ( - Prohibited RejectionReason = iota + 1 - ConnectionFailed - UnknownChannelType - ResourceShortage -) - -// String converts the rejection reason to human readable form. -func (r RejectionReason) String() string { - switch r { - case Prohibited: - return "administratively prohibited" - case ConnectionFailed: - return "connect failed" - case UnknownChannelType: - return "unknown channel type" - case ResourceShortage: - return "resource shortage" - } - return fmt.Sprintf("unknown reason %d", int(r)) -} - -func min(a uint32, b int) uint32 { - if a < uint32(b) { - return a - } - return uint32(b) -} - -type channelDirection uint8 - -const ( - channelInbound channelDirection = iota - channelOutbound -) - -// channel is an implementation of the Channel interface that works -// with the mux class. -type channel struct { - // R/O after creation - chanType string - extraData []byte - localId, remoteId uint32 - - // maxIncomingPayload and maxRemotePayload are the maximum - // payload sizes of normal and extended data packets for - // receiving and sending, respectively. The wire packet will - // be 9 or 13 bytes larger (excluding encryption overhead). - maxIncomingPayload uint32 - maxRemotePayload uint32 - - mux *mux - - // decided is set to true if an accept or reject message has been sent - // (for outbound channels) or received (for inbound channels). - decided bool - - // direction contains either channelOutbound, for channels created - // locally, or channelInbound, for channels created by the peer. - direction channelDirection - - // Pending internal channel messages. - msg chan interface{} - - // Since requests have no ID, there can be only one request - // with WantReply=true outstanding. This lock is held by a - // goroutine that has such an outgoing request pending. - sentRequestMu sync.Mutex - - incomingRequests chan *Request - - sentEOF bool - - // thread-safe data - remoteWin window - pending *buffer - extPending *buffer - - // windowMu protects myWindow, the flow-control window. - windowMu sync.Mutex - myWindow uint32 - - // writeMu serializes calls to mux.conn.writePacket() and - // protects sentClose and packetPool. This mutex must be - // different from windowMu, as writePacket can block if there - // is a key exchange pending. - writeMu sync.Mutex - sentClose bool - - // packetPool has a buffer for each extended channel ID to - // save allocations during writes. - packetPool map[uint32][]byte -} - -// writePacket sends a packet. If the packet is a channel close, it updates -// sentClose. This method takes the lock c.writeMu. -func (c *channel) writePacket(packet []byte) error { - c.writeMu.Lock() - if c.sentClose { - c.writeMu.Unlock() - return io.EOF - } - c.sentClose = (packet[0] == msgChannelClose) - err := c.mux.conn.writePacket(packet) - c.writeMu.Unlock() - return err -} - -func (c *channel) sendMessage(msg interface{}) error { - if debugMux { - log.Printf("send(%d): %#v", c.mux.chanList.offset, msg) - } - - p := Marshal(msg) - binary.BigEndian.PutUint32(p[1:], c.remoteId) - return c.writePacket(p) -} - -// WriteExtended writes data to a specific extended stream. These streams are -// used, for example, for stderr. -func (c *channel) WriteExtended(data []byte, extendedCode uint32) (n int, err error) { - if c.sentEOF { - return 0, io.EOF - } - // 1 byte message type, 4 bytes remoteId, 4 bytes data length - opCode := byte(msgChannelData) - headerLength := uint32(9) - if extendedCode > 0 { - headerLength += 4 - opCode = msgChannelExtendedData - } - - c.writeMu.Lock() - packet := c.packetPool[extendedCode] - // We don't remove the buffer from packetPool, so - // WriteExtended calls from different goroutines will be - // flagged as errors by the race detector. - c.writeMu.Unlock() - - for len(data) > 0 { - space := min(c.maxRemotePayload, len(data)) - if space, err = c.remoteWin.reserve(space); err != nil { - return n, err - } - if want := headerLength + space; uint32(cap(packet)) < want { - packet = make([]byte, want) - } else { - packet = packet[:want] - } - - todo := data[:space] - - packet[0] = opCode - binary.BigEndian.PutUint32(packet[1:], c.remoteId) - if extendedCode > 0 { - binary.BigEndian.PutUint32(packet[5:], uint32(extendedCode)) - } - binary.BigEndian.PutUint32(packet[headerLength-4:], uint32(len(todo))) - copy(packet[headerLength:], todo) - if err = c.writePacket(packet); err != nil { - return n, err - } - - n += len(todo) - data = data[len(todo):] - } - - c.writeMu.Lock() - c.packetPool[extendedCode] = packet - c.writeMu.Unlock() - - return n, err -} - -func (c *channel) handleData(packet []byte) error { - headerLen := 9 - isExtendedData := packet[0] == msgChannelExtendedData - if isExtendedData { - headerLen = 13 - } - if len(packet) < headerLen { - // malformed data packet - return parseError(packet[0]) - } - - var extended uint32 - if isExtendedData { - extended = binary.BigEndian.Uint32(packet[5:]) - } - - length := binary.BigEndian.Uint32(packet[headerLen-4 : headerLen]) - if length == 0 { - return nil - } - if length > c.maxIncomingPayload { - // TODO(hanwen): should send Disconnect? - return errors.New("ssh: incoming packet exceeds maximum payload size") - } - - data := packet[headerLen:] - if length != uint32(len(data)) { - return errors.New("ssh: wrong packet length") - } - - c.windowMu.Lock() - if c.myWindow < length { - c.windowMu.Unlock() - // TODO(hanwen): should send Disconnect with reason? - return errors.New("ssh: remote side wrote too much") - } - c.myWindow -= length - c.windowMu.Unlock() - - if extended == 1 { - c.extPending.write(data) - } else if extended > 0 { - // discard other extended data. - } else { - c.pending.write(data) - } - return nil -} - -func (c *channel) adjustWindow(n uint32) error { - c.windowMu.Lock() - // Since myWindow is managed on our side, and can never exceed - // the initial window setting, we don't worry about overflow. - c.myWindow += uint32(n) - c.windowMu.Unlock() - return c.sendMessage(windowAdjustMsg{ - AdditionalBytes: uint32(n), - }) -} - -func (c *channel) ReadExtended(data []byte, extended uint32) (n int, err error) { - switch extended { - case 1: - n, err = c.extPending.Read(data) - case 0: - n, err = c.pending.Read(data) - default: - return 0, fmt.Errorf("ssh: extended code %d unimplemented", extended) - } - - if n > 0 { - err = c.adjustWindow(uint32(n)) - // sendWindowAdjust can return io.EOF if the remote - // peer has closed the connection, however we want to - // defer forwarding io.EOF to the caller of Read until - // the buffer has been drained. - if n > 0 && err == io.EOF { - err = nil - } - } - - return n, err -} - -func (c *channel) close() { - c.pending.eof() - c.extPending.eof() - close(c.msg) - close(c.incomingRequests) - c.writeMu.Lock() - // This is not necessary for a normal channel teardown, but if - // there was another error, it is. - c.sentClose = true - c.writeMu.Unlock() - // Unblock writers. - c.remoteWin.close() -} - -// responseMessageReceived is called when a success or failure message is -// received on a channel to check that such a message is reasonable for the -// given channel. -func (c *channel) responseMessageReceived() error { - if c.direction == channelInbound { - return errors.New("ssh: channel response message received on inbound channel") - } - if c.decided { - return errors.New("ssh: duplicate response received for channel") - } - c.decided = true - return nil -} - -func (c *channel) handlePacket(packet []byte) error { - switch packet[0] { - case msgChannelData, msgChannelExtendedData: - return c.handleData(packet) - case msgChannelClose: - c.sendMessage(channelCloseMsg{PeersId: c.remoteId}) - c.mux.chanList.remove(c.localId) - c.close() - return nil - case msgChannelEOF: - // RFC 4254 is mute on how EOF affects dataExt messages but - // it is logical to signal EOF at the same time. - c.extPending.eof() - c.pending.eof() - return nil - } - - decoded, err := decode(packet) - if err != nil { - return err - } - - switch msg := decoded.(type) { - case *channelOpenFailureMsg: - if err := c.responseMessageReceived(); err != nil { - return err - } - c.mux.chanList.remove(msg.PeersId) - c.msg <- msg - case *channelOpenConfirmMsg: - if err := c.responseMessageReceived(); err != nil { - return err - } - if msg.MaxPacketSize < minPacketLength || msg.MaxPacketSize > 1<<31 { - return fmt.Errorf("ssh: invalid MaxPacketSize %d from peer", msg.MaxPacketSize) - } - c.remoteId = msg.MyId - c.maxRemotePayload = msg.MaxPacketSize - c.remoteWin.add(msg.MyWindow) - c.msg <- msg - case *windowAdjustMsg: - if !c.remoteWin.add(msg.AdditionalBytes) { - return fmt.Errorf("ssh: invalid window update for %d bytes", msg.AdditionalBytes) - } - case *channelRequestMsg: - req := Request{ - Type: msg.Request, - WantReply: msg.WantReply, - Payload: msg.RequestSpecificData, - ch: c, - } - - c.incomingRequests <- &req - default: - c.msg <- msg - } - return nil -} - -func (m *mux) newChannel(chanType string, direction channelDirection, extraData []byte) *channel { - ch := &channel{ - remoteWin: window{Cond: newCond()}, - myWindow: channelWindowSize, - pending: newBuffer(), - extPending: newBuffer(), - direction: direction, - incomingRequests: make(chan *Request, 16), - msg: make(chan interface{}, 16), - chanType: chanType, - extraData: extraData, - mux: m, - packetPool: make(map[uint32][]byte), - } - ch.localId = m.chanList.add(ch) - return ch -} - -var errUndecided = errors.New("ssh: must Accept or Reject channel") -var errDecidedAlready = errors.New("ssh: can call Accept or Reject only once") - -type extChannel struct { - code uint32 - ch *channel -} - -func (e *extChannel) Write(data []byte) (n int, err error) { - return e.ch.WriteExtended(data, e.code) -} - -func (e *extChannel) Read(data []byte) (n int, err error) { - return e.ch.ReadExtended(data, e.code) -} - -func (c *channel) Accept() (Channel, <-chan *Request, error) { - if c.decided { - return nil, nil, errDecidedAlready - } - c.maxIncomingPayload = channelMaxPacket - confirm := channelOpenConfirmMsg{ - PeersId: c.remoteId, - MyId: c.localId, - MyWindow: c.myWindow, - MaxPacketSize: c.maxIncomingPayload, - } - c.decided = true - if err := c.sendMessage(confirm); err != nil { - return nil, nil, err - } - - return c, c.incomingRequests, nil -} - -func (ch *channel) Reject(reason RejectionReason, message string) error { - if ch.decided { - return errDecidedAlready - } - reject := channelOpenFailureMsg{ - PeersId: ch.remoteId, - Reason: reason, - Message: message, - Language: "en", - } - ch.decided = true - return ch.sendMessage(reject) -} - -func (ch *channel) Read(data []byte) (int, error) { - if !ch.decided { - return 0, errUndecided - } - return ch.ReadExtended(data, 0) -} - -func (ch *channel) Write(data []byte) (int, error) { - if !ch.decided { - return 0, errUndecided - } - return ch.WriteExtended(data, 0) -} - -func (ch *channel) CloseWrite() error { - if !ch.decided { - return errUndecided - } - ch.sentEOF = true - return ch.sendMessage(channelEOFMsg{ - PeersId: ch.remoteId}) -} - -func (ch *channel) Close() error { - if !ch.decided { - return errUndecided - } - - return ch.sendMessage(channelCloseMsg{ - PeersId: ch.remoteId}) -} - -// Extended returns an io.ReadWriter that sends and receives data on the given, -// SSH extended stream. Such streams are used, for example, for stderr. -func (ch *channel) Extended(code uint32) io.ReadWriter { - if !ch.decided { - return nil - } - return &extChannel{code, ch} -} - -func (ch *channel) Stderr() io.ReadWriter { - return ch.Extended(1) -} - -func (ch *channel) SendRequest(name string, wantReply bool, payload []byte) (bool, error) { - if !ch.decided { - return false, errUndecided - } - - if wantReply { - ch.sentRequestMu.Lock() - defer ch.sentRequestMu.Unlock() - } - - msg := channelRequestMsg{ - PeersId: ch.remoteId, - Request: name, - WantReply: wantReply, - RequestSpecificData: payload, - } - - if err := ch.sendMessage(msg); err != nil { - return false, err - } - - if wantReply { - m, ok := (<-ch.msg) - if !ok { - return false, io.EOF - } - switch m.(type) { - case *channelRequestFailureMsg: - return false, nil - case *channelRequestSuccessMsg: - return true, nil - default: - return false, fmt.Errorf("ssh: unexpected response to channel request: %#v", m) - } - } - - return false, nil -} - -// ackRequest either sends an ack or nack to the channel request. -func (ch *channel) ackRequest(ok bool) error { - if !ch.decided { - return errUndecided - } - - var msg interface{} - if !ok { - msg = channelRequestFailureMsg{ - PeersId: ch.remoteId, - } - } else { - msg = channelRequestSuccessMsg{ - PeersId: ch.remoteId, - } - } - return ch.sendMessage(msg) -} - -func (ch *channel) ChannelType() string { - return ch.chanType -} - -func (ch *channel) ExtraData() []byte { - return ch.extraData -} diff --git a/vendor/golang.org/x/crypto/ssh/cipher.go b/vendor/golang.org/x/crypto/ssh/cipher.go deleted file mode 100644 index 34d3917..0000000 --- a/vendor/golang.org/x/crypto/ssh/cipher.go +++ /dev/null @@ -1,579 +0,0 @@ -// Copyright 2011 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 ssh - -import ( - "crypto/aes" - "crypto/cipher" - "crypto/des" - "crypto/rc4" - "crypto/subtle" - "encoding/binary" - "errors" - "fmt" - "hash" - "io" - "io/ioutil" -) - -const ( - packetSizeMultiple = 16 // TODO(huin) this should be determined by the cipher. - - // RFC 4253 section 6.1 defines a minimum packet size of 32768 that implementations - // MUST be able to process (plus a few more kilobytes for padding and mac). The RFC - // indicates implementations SHOULD be able to handle larger packet sizes, but then - // waffles on about reasonable limits. - // - // OpenSSH caps their maxPacket at 256kB so we choose to do - // the same. maxPacket is also used to ensure that uint32 - // length fields do not overflow, so it should remain well - // below 4G. - maxPacket = 256 * 1024 -) - -// noneCipher implements cipher.Stream and provides no encryption. It is used -// by the transport before the first key-exchange. -type noneCipher struct{} - -func (c noneCipher) XORKeyStream(dst, src []byte) { - copy(dst, src) -} - -func newAESCTR(key, iv []byte) (cipher.Stream, error) { - c, err := aes.NewCipher(key) - if err != nil { - return nil, err - } - return cipher.NewCTR(c, iv), nil -} - -func newRC4(key, iv []byte) (cipher.Stream, error) { - return rc4.NewCipher(key) -} - -type streamCipherMode struct { - keySize int - ivSize int - skip int - createFunc func(key, iv []byte) (cipher.Stream, error) -} - -func (c *streamCipherMode) createStream(key, iv []byte) (cipher.Stream, error) { - if len(key) < c.keySize { - panic("ssh: key length too small for cipher") - } - if len(iv) < c.ivSize { - panic("ssh: iv too small for cipher") - } - - stream, err := c.createFunc(key[:c.keySize], iv[:c.ivSize]) - if err != nil { - return nil, err - } - - var streamDump []byte - if c.skip > 0 { - streamDump = make([]byte, 512) - } - - for remainingToDump := c.skip; remainingToDump > 0; { - dumpThisTime := remainingToDump - if dumpThisTime > len(streamDump) { - dumpThisTime = len(streamDump) - } - stream.XORKeyStream(streamDump[:dumpThisTime], streamDump[:dumpThisTime]) - remainingToDump -= dumpThisTime - } - - return stream, nil -} - -// cipherModes documents properties of supported ciphers. Ciphers not included -// are not supported and will not be negotiated, even if explicitly requested in -// ClientConfig.Crypto.Ciphers. -var cipherModes = map[string]*streamCipherMode{ - // Ciphers from RFC4344, which introduced many CTR-based ciphers. Algorithms - // are defined in the order specified in the RFC. - "aes128-ctr": {16, aes.BlockSize, 0, newAESCTR}, - "aes192-ctr": {24, aes.BlockSize, 0, newAESCTR}, - "aes256-ctr": {32, aes.BlockSize, 0, newAESCTR}, - - // Ciphers from RFC4345, which introduces security-improved arcfour ciphers. - // They are defined in the order specified in the RFC. - "arcfour128": {16, 0, 1536, newRC4}, - "arcfour256": {32, 0, 1536, newRC4}, - - // Cipher defined in RFC 4253, which describes SSH Transport Layer Protocol. - // Note that this cipher is not safe, as stated in RFC 4253: "Arcfour (and - // RC4) has problems with weak keys, and should be used with caution." - // RFC4345 introduces improved versions of Arcfour. - "arcfour": {16, 0, 0, newRC4}, - - // AES-GCM is not a stream cipher, so it is constructed with a - // special case. If we add any more non-stream ciphers, we - // should invest a cleaner way to do this. - gcmCipherID: {16, 12, 0, nil}, - - // CBC mode is insecure and so is not included in the default config. - // (See http://www.isg.rhul.ac.uk/~kp/SandPfinal.pdf). If absolutely - // needed, it's possible to specify a custom Config to enable it. - // You should expect that an active attacker can recover plaintext if - // you do. - aes128cbcID: {16, aes.BlockSize, 0, nil}, - - // 3des-cbc is insecure and is disabled by default. - tripledescbcID: {24, des.BlockSize, 0, nil}, -} - -// prefixLen is the length of the packet prefix that contains the packet length -// and number of padding bytes. -const prefixLen = 5 - -// streamPacketCipher is a packetCipher using a stream cipher. -type streamPacketCipher struct { - mac hash.Hash - cipher cipher.Stream - - // The following members are to avoid per-packet allocations. - prefix [prefixLen]byte - seqNumBytes [4]byte - padding [2 * packetSizeMultiple]byte - packetData []byte - macResult []byte -} - -// readPacket reads and decrypt a single packet from the reader argument. -func (s *streamPacketCipher) readPacket(seqNum uint32, r io.Reader) ([]byte, error) { - if _, err := io.ReadFull(r, s.prefix[:]); err != nil { - return nil, err - } - - s.cipher.XORKeyStream(s.prefix[:], s.prefix[:]) - length := binary.BigEndian.Uint32(s.prefix[0:4]) - paddingLength := uint32(s.prefix[4]) - - var macSize uint32 - if s.mac != nil { - s.mac.Reset() - binary.BigEndian.PutUint32(s.seqNumBytes[:], seqNum) - s.mac.Write(s.seqNumBytes[:]) - s.mac.Write(s.prefix[:]) - macSize = uint32(s.mac.Size()) - } - - if length <= paddingLength+1 { - return nil, errors.New("ssh: invalid packet length, packet too small") - } - - if length > maxPacket { - return nil, errors.New("ssh: invalid packet length, packet too large") - } - - // the maxPacket check above ensures that length-1+macSize - // does not overflow. - if uint32(cap(s.packetData)) < length-1+macSize { - s.packetData = make([]byte, length-1+macSize) - } else { - s.packetData = s.packetData[:length-1+macSize] - } - - if _, err := io.ReadFull(r, s.packetData); err != nil { - return nil, err - } - mac := s.packetData[length-1:] - data := s.packetData[:length-1] - s.cipher.XORKeyStream(data, data) - - if s.mac != nil { - s.mac.Write(data) - s.macResult = s.mac.Sum(s.macResult[:0]) - if subtle.ConstantTimeCompare(s.macResult, mac) != 1 { - return nil, errors.New("ssh: MAC failure") - } - } - - return s.packetData[:length-paddingLength-1], nil -} - -// writePacket encrypts and sends a packet of data to the writer argument -func (s *streamPacketCipher) writePacket(seqNum uint32, w io.Writer, rand io.Reader, packet []byte) error { - if len(packet) > maxPacket { - return errors.New("ssh: packet too large") - } - - paddingLength := packetSizeMultiple - (prefixLen+len(packet))%packetSizeMultiple - if paddingLength < 4 { - paddingLength += packetSizeMultiple - } - - length := len(packet) + 1 + paddingLength - binary.BigEndian.PutUint32(s.prefix[:], uint32(length)) - s.prefix[4] = byte(paddingLength) - padding := s.padding[:paddingLength] - if _, err := io.ReadFull(rand, padding); err != nil { - return err - } - - if s.mac != nil { - s.mac.Reset() - binary.BigEndian.PutUint32(s.seqNumBytes[:], seqNum) - s.mac.Write(s.seqNumBytes[:]) - s.mac.Write(s.prefix[:]) - s.mac.Write(packet) - s.mac.Write(padding) - } - - s.cipher.XORKeyStream(s.prefix[:], s.prefix[:]) - s.cipher.XORKeyStream(packet, packet) - s.cipher.XORKeyStream(padding, padding) - - if _, err := w.Write(s.prefix[:]); err != nil { - return err - } - if _, err := w.Write(packet); err != nil { - return err - } - if _, err := w.Write(padding); err != nil { - return err - } - - if s.mac != nil { - s.macResult = s.mac.Sum(s.macResult[:0]) - if _, err := w.Write(s.macResult); err != nil { - return err - } - } - - return nil -} - -type gcmCipher struct { - aead cipher.AEAD - prefix [4]byte - iv []byte - buf []byte -} - -func newGCMCipher(iv, key, macKey []byte) (packetCipher, error) { - c, err := aes.NewCipher(key) - if err != nil { - return nil, err - } - - aead, err := cipher.NewGCM(c) - if err != nil { - return nil, err - } - - return &gcmCipher{ - aead: aead, - iv: iv, - }, nil -} - -const gcmTagSize = 16 - -func (c *gcmCipher) writePacket(seqNum uint32, w io.Writer, rand io.Reader, packet []byte) error { - // Pad out to multiple of 16 bytes. This is different from the - // stream cipher because that encrypts the length too. - padding := byte(packetSizeMultiple - (1+len(packet))%packetSizeMultiple) - if padding < 4 { - padding += packetSizeMultiple - } - - length := uint32(len(packet) + int(padding) + 1) - binary.BigEndian.PutUint32(c.prefix[:], length) - if _, err := w.Write(c.prefix[:]); err != nil { - return err - } - - if cap(c.buf) < int(length) { - c.buf = make([]byte, length) - } else { - c.buf = c.buf[:length] - } - - c.buf[0] = padding - copy(c.buf[1:], packet) - if _, err := io.ReadFull(rand, c.buf[1+len(packet):]); err != nil { - return err - } - c.buf = c.aead.Seal(c.buf[:0], c.iv, c.buf, c.prefix[:]) - if _, err := w.Write(c.buf); err != nil { - return err - } - c.incIV() - - return nil -} - -func (c *gcmCipher) incIV() { - for i := 4 + 7; i >= 4; i-- { - c.iv[i]++ - if c.iv[i] != 0 { - break - } - } -} - -func (c *gcmCipher) readPacket(seqNum uint32, r io.Reader) ([]byte, error) { - if _, err := io.ReadFull(r, c.prefix[:]); err != nil { - return nil, err - } - length := binary.BigEndian.Uint32(c.prefix[:]) - if length > maxPacket { - return nil, errors.New("ssh: max packet length exceeded.") - } - - if cap(c.buf) < int(length+gcmTagSize) { - c.buf = make([]byte, length+gcmTagSize) - } else { - c.buf = c.buf[:length+gcmTagSize] - } - - if _, err := io.ReadFull(r, c.buf); err != nil { - return nil, err - } - - plain, err := c.aead.Open(c.buf[:0], c.iv, c.buf, c.prefix[:]) - if err != nil { - return nil, err - } - c.incIV() - - padding := plain[0] - if padding < 4 || padding >= 20 { - return nil, fmt.Errorf("ssh: illegal padding %d", padding) - } - - if int(padding+1) >= len(plain) { - return nil, fmt.Errorf("ssh: padding %d too large", padding) - } - plain = plain[1 : length-uint32(padding)] - return plain, nil -} - -// cbcCipher implements aes128-cbc cipher defined in RFC 4253 section 6.1 -type cbcCipher struct { - mac hash.Hash - macSize uint32 - decrypter cipher.BlockMode - encrypter cipher.BlockMode - - // The following members are to avoid per-packet allocations. - seqNumBytes [4]byte - packetData []byte - macResult []byte - - // Amount of data we should still read to hide which - // verification error triggered. - oracleCamouflage uint32 -} - -func newCBCCipher(c cipher.Block, iv, key, macKey []byte, algs directionAlgorithms) (packetCipher, error) { - cbc := &cbcCipher{ - mac: macModes[algs.MAC].new(macKey), - decrypter: cipher.NewCBCDecrypter(c, iv), - encrypter: cipher.NewCBCEncrypter(c, iv), - packetData: make([]byte, 1024), - } - if cbc.mac != nil { - cbc.macSize = uint32(cbc.mac.Size()) - } - - return cbc, nil -} - -func newAESCBCCipher(iv, key, macKey []byte, algs directionAlgorithms) (packetCipher, error) { - c, err := aes.NewCipher(key) - if err != nil { - return nil, err - } - - cbc, err := newCBCCipher(c, iv, key, macKey, algs) - if err != nil { - return nil, err - } - - return cbc, nil -} - -func newTripleDESCBCCipher(iv, key, macKey []byte, algs directionAlgorithms) (packetCipher, error) { - c, err := des.NewTripleDESCipher(key) - if err != nil { - return nil, err - } - - cbc, err := newCBCCipher(c, iv, key, macKey, algs) - if err != nil { - return nil, err - } - - return cbc, nil -} - -func maxUInt32(a, b int) uint32 { - if a > b { - return uint32(a) - } - return uint32(b) -} - -const ( - cbcMinPacketSizeMultiple = 8 - cbcMinPacketSize = 16 - cbcMinPaddingSize = 4 -) - -// cbcError represents a verification error that may leak information. -type cbcError string - -func (e cbcError) Error() string { return string(e) } - -func (c *cbcCipher) readPacket(seqNum uint32, r io.Reader) ([]byte, error) { - p, err := c.readPacketLeaky(seqNum, r) - if err != nil { - if _, ok := err.(cbcError); ok { - // Verification error: read a fixed amount of - // data, to make distinguishing between - // failing MAC and failing length check more - // difficult. - io.CopyN(ioutil.Discard, r, int64(c.oracleCamouflage)) - } - } - return p, err -} - -func (c *cbcCipher) readPacketLeaky(seqNum uint32, r io.Reader) ([]byte, error) { - blockSize := c.decrypter.BlockSize() - - // Read the header, which will include some of the subsequent data in the - // case of block ciphers - this is copied back to the payload later. - // How many bytes of payload/padding will be read with this first read. - firstBlockLength := uint32((prefixLen + blockSize - 1) / blockSize * blockSize) - firstBlock := c.packetData[:firstBlockLength] - if _, err := io.ReadFull(r, firstBlock); err != nil { - return nil, err - } - - c.oracleCamouflage = maxPacket + 4 + c.macSize - firstBlockLength - - c.decrypter.CryptBlocks(firstBlock, firstBlock) - length := binary.BigEndian.Uint32(firstBlock[:4]) - if length > maxPacket { - return nil, cbcError("ssh: packet too large") - } - if length+4 < maxUInt32(cbcMinPacketSize, blockSize) { - // The minimum size of a packet is 16 (or the cipher block size, whichever - // is larger) bytes. - return nil, cbcError("ssh: packet too small") - } - // The length of the packet (including the length field but not the MAC) must - // be a multiple of the block size or 8, whichever is larger. - if (length+4)%maxUInt32(cbcMinPacketSizeMultiple, blockSize) != 0 { - return nil, cbcError("ssh: invalid packet length multiple") - } - - paddingLength := uint32(firstBlock[4]) - if paddingLength < cbcMinPaddingSize || length <= paddingLength+1 { - return nil, cbcError("ssh: invalid packet length") - } - - // Positions within the c.packetData buffer: - macStart := 4 + length - paddingStart := macStart - paddingLength - - // Entire packet size, starting before length, ending at end of mac. - entirePacketSize := macStart + c.macSize - - // Ensure c.packetData is large enough for the entire packet data. - if uint32(cap(c.packetData)) < entirePacketSize { - // Still need to upsize and copy, but this should be rare at runtime, only - // on upsizing the packetData buffer. - c.packetData = make([]byte, entirePacketSize) - copy(c.packetData, firstBlock) - } else { - c.packetData = c.packetData[:entirePacketSize] - } - - if n, err := io.ReadFull(r, c.packetData[firstBlockLength:]); err != nil { - return nil, err - } else { - c.oracleCamouflage -= uint32(n) - } - - remainingCrypted := c.packetData[firstBlockLength:macStart] - c.decrypter.CryptBlocks(remainingCrypted, remainingCrypted) - - mac := c.packetData[macStart:] - if c.mac != nil { - c.mac.Reset() - binary.BigEndian.PutUint32(c.seqNumBytes[:], seqNum) - c.mac.Write(c.seqNumBytes[:]) - c.mac.Write(c.packetData[:macStart]) - c.macResult = c.mac.Sum(c.macResult[:0]) - if subtle.ConstantTimeCompare(c.macResult, mac) != 1 { - return nil, cbcError("ssh: MAC failure") - } - } - - return c.packetData[prefixLen:paddingStart], nil -} - -func (c *cbcCipher) writePacket(seqNum uint32, w io.Writer, rand io.Reader, packet []byte) error { - effectiveBlockSize := maxUInt32(cbcMinPacketSizeMultiple, c.encrypter.BlockSize()) - - // Length of encrypted portion of the packet (header, payload, padding). - // Enforce minimum padding and packet size. - encLength := maxUInt32(prefixLen+len(packet)+cbcMinPaddingSize, cbcMinPaddingSize) - // Enforce block size. - encLength = (encLength + effectiveBlockSize - 1) / effectiveBlockSize * effectiveBlockSize - - length := encLength - 4 - paddingLength := int(length) - (1 + len(packet)) - - // Overall buffer contains: header, payload, padding, mac. - // Space for the MAC is reserved in the capacity but not the slice length. - bufferSize := encLength + c.macSize - if uint32(cap(c.packetData)) < bufferSize { - c.packetData = make([]byte, encLength, bufferSize) - } else { - c.packetData = c.packetData[:encLength] - } - - p := c.packetData - - // Packet header. - binary.BigEndian.PutUint32(p, length) - p = p[4:] - p[0] = byte(paddingLength) - - // Payload. - p = p[1:] - copy(p, packet) - - // Padding. - p = p[len(packet):] - if _, err := io.ReadFull(rand, p); err != nil { - return err - } - - if c.mac != nil { - c.mac.Reset() - binary.BigEndian.PutUint32(c.seqNumBytes[:], seqNum) - c.mac.Write(c.seqNumBytes[:]) - c.mac.Write(c.packetData) - // The MAC is now appended into the capacity reserved for it earlier. - c.packetData = c.mac.Sum(c.packetData) - } - - c.encrypter.CryptBlocks(c.packetData[:encLength], c.packetData[:encLength]) - - if _, err := w.Write(c.packetData); err != nil { - return err - } - - return nil -} diff --git a/vendor/golang.org/x/crypto/ssh/client.go b/vendor/golang.org/x/crypto/ssh/client.go deleted file mode 100644 index 0212a20..0000000 --- a/vendor/golang.org/x/crypto/ssh/client.go +++ /dev/null @@ -1,213 +0,0 @@ -// Copyright 2011 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 ssh - -import ( - "errors" - "fmt" - "net" - "sync" - "time" -) - -// Client implements a traditional SSH client that supports shells, -// subprocesses, port forwarding and tunneled dialing. -type Client struct { - Conn - - forwards forwardList // forwarded tcpip connections from the remote side - mu sync.Mutex - channelHandlers map[string]chan NewChannel -} - -// HandleChannelOpen returns a channel on which NewChannel requests -// for the given type are sent. If the type already is being handled, -// nil is returned. The channel is closed when the connection is closed. -func (c *Client) HandleChannelOpen(channelType string) <-chan NewChannel { - c.mu.Lock() - defer c.mu.Unlock() - if c.channelHandlers == nil { - // The SSH channel has been closed. - c := make(chan NewChannel) - close(c) - return c - } - - ch := c.channelHandlers[channelType] - if ch != nil { - return nil - } - - ch = make(chan NewChannel, 16) - c.channelHandlers[channelType] = ch - return ch -} - -// NewClient creates a Client on top of the given connection. -func NewClient(c Conn, chans <-chan NewChannel, reqs <-chan *Request) *Client { - conn := &Client{ - Conn: c, - channelHandlers: make(map[string]chan NewChannel, 1), - } - - go conn.handleGlobalRequests(reqs) - go conn.handleChannelOpens(chans) - go func() { - conn.Wait() - conn.forwards.closeAll() - }() - go conn.forwards.handleChannels(conn.HandleChannelOpen("forwarded-tcpip")) - return conn -} - -// NewClientConn establishes an authenticated SSH connection using c -// as the underlying transport. The Request and NewChannel channels -// must be serviced or the connection will hang. -func NewClientConn(c net.Conn, addr string, config *ClientConfig) (Conn, <-chan NewChannel, <-chan *Request, error) { - fullConf := *config - fullConf.SetDefaults() - conn := &connection{ - sshConn: sshConn{conn: c}, - } - - if err := conn.clientHandshake(addr, &fullConf); err != nil { - c.Close() - return nil, nil, nil, fmt.Errorf("ssh: handshake failed: %v", err) - } - conn.mux = newMux(conn.transport) - return conn, conn.mux.incomingChannels, conn.mux.incomingRequests, nil -} - -// clientHandshake performs the client side key exchange. See RFC 4253 Section -// 7. -func (c *connection) clientHandshake(dialAddress string, config *ClientConfig) error { - if config.ClientVersion != "" { - c.clientVersion = []byte(config.ClientVersion) - } else { - c.clientVersion = []byte(packageVersion) - } - var err error - c.serverVersion, err = exchangeVersions(c.sshConn.conn, c.clientVersion) - if err != nil { - return err - } - - c.transport = newClientTransport( - newTransport(c.sshConn.conn, config.Rand, true /* is client */), - c.clientVersion, c.serverVersion, config, dialAddress, c.sshConn.RemoteAddr()) - if err := c.transport.requestInitialKeyChange(); err != nil { - return err - } - - // We just did the key change, so the session ID is established. - c.sessionID = c.transport.getSessionID() - - return c.clientAuthenticate(config) -} - -// verifyHostKeySignature verifies the host key obtained in the key -// exchange. -func verifyHostKeySignature(hostKey PublicKey, result *kexResult) error { - sig, rest, ok := parseSignatureBody(result.Signature) - if len(rest) > 0 || !ok { - return errors.New("ssh: signature parse error") - } - - return hostKey.Verify(result.H, sig) -} - -// NewSession opens a new Session for this client. (A session is a remote -// execution of a program.) -func (c *Client) NewSession() (*Session, error) { - ch, in, err := c.OpenChannel("session", nil) - if err != nil { - return nil, err - } - return newSession(ch, in) -} - -func (c *Client) handleGlobalRequests(incoming <-chan *Request) { - for r := range incoming { - // This handles keepalive messages and matches - // the behaviour of OpenSSH. - r.Reply(false, nil) - } -} - -// handleChannelOpens channel open messages from the remote side. -func (c *Client) handleChannelOpens(in <-chan NewChannel) { - for ch := range in { - c.mu.Lock() - handler := c.channelHandlers[ch.ChannelType()] - c.mu.Unlock() - - if handler != nil { - handler <- ch - } else { - ch.Reject(UnknownChannelType, fmt.Sprintf("unknown channel type: %v", ch.ChannelType())) - } - } - - c.mu.Lock() - for _, ch := range c.channelHandlers { - close(ch) - } - c.channelHandlers = nil - c.mu.Unlock() -} - -// Dial starts a client connection to the given SSH server. It is a -// convenience function that connects to the given network address, -// initiates the SSH handshake, and then sets up a Client. For access -// to incoming channels and requests, use net.Dial with NewClientConn -// instead. -func Dial(network, addr string, config *ClientConfig) (*Client, error) { - conn, err := net.DialTimeout(network, addr, config.Timeout) - if err != nil { - return nil, err - } - c, chans, reqs, err := NewClientConn(conn, addr, config) - if err != nil { - return nil, err - } - return NewClient(c, chans, reqs), nil -} - -// A ClientConfig structure is used to configure a Client. It must not be -// modified after having been passed to an SSH function. -type ClientConfig struct { - // Config contains configuration that is shared between clients and - // servers. - Config - - // User contains the username to authenticate as. - User string - - // Auth contains possible authentication methods to use with the - // server. Only the first instance of a particular RFC 4252 method will - // be used during authentication. - Auth []AuthMethod - - // HostKeyCallback, if not nil, is called during the cryptographic - // handshake to validate the server's host key. A nil HostKeyCallback - // implies that all host keys are accepted. - HostKeyCallback func(hostname string, remote net.Addr, key PublicKey) error - - // ClientVersion contains the version identification string that will - // be used for the connection. If empty, a reasonable default is used. - ClientVersion string - - // HostKeyAlgorithms lists the key types that the client will - // accept from the server as host key, in order of - // preference. If empty, a reasonable default is used. Any - // string returned from PublicKey.Type method may be used, or - // any of the CertAlgoXxxx and KeyAlgoXxxx constants. - HostKeyAlgorithms []string - - // Timeout is the maximum amount of time for the TCP connection to establish. - // - // A Timeout of zero means no timeout. - Timeout time.Duration -} diff --git a/vendor/golang.org/x/crypto/ssh/client_auth.go b/vendor/golang.org/x/crypto/ssh/client_auth.go deleted file mode 100644 index 294af0d..0000000 --- a/vendor/golang.org/x/crypto/ssh/client_auth.go +++ /dev/null @@ -1,473 +0,0 @@ -// Copyright 2011 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 ssh - -import ( - "bytes" - "errors" - "fmt" - "io" -) - -// clientAuthenticate authenticates with the remote server. See RFC 4252. -func (c *connection) clientAuthenticate(config *ClientConfig) error { - // initiate user auth session - if err := c.transport.writePacket(Marshal(&serviceRequestMsg{serviceUserAuth})); err != nil { - return err - } - packet, err := c.transport.readPacket() - if err != nil { - return err - } - var serviceAccept serviceAcceptMsg - if err := Unmarshal(packet, &serviceAccept); err != nil { - return err - } - - // during the authentication phase the client first attempts the "none" method - // then any untried methods suggested by the server. - tried := make(map[string]bool) - var lastMethods []string - for auth := AuthMethod(new(noneAuth)); auth != nil; { - ok, methods, err := auth.auth(c.transport.getSessionID(), config.User, c.transport, config.Rand) - if err != nil { - return err - } - if ok { - // success - return nil - } - tried[auth.method()] = true - if methods == nil { - methods = lastMethods - } - lastMethods = methods - - auth = nil - - findNext: - for _, a := range config.Auth { - candidateMethod := a.method() - if tried[candidateMethod] { - continue - } - for _, meth := range methods { - if meth == candidateMethod { - auth = a - break findNext - } - } - } - } - return fmt.Errorf("ssh: unable to authenticate, attempted methods %v, no supported methods remain", keys(tried)) -} - -func keys(m map[string]bool) []string { - s := make([]string, 0, len(m)) - - for key := range m { - s = append(s, key) - } - return s -} - -// An AuthMethod represents an instance of an RFC 4252 authentication method. -type AuthMethod interface { - // auth authenticates user over transport t. - // Returns true if authentication is successful. - // If authentication is not successful, a []string of alternative - // method names is returned. If the slice is nil, it will be ignored - // and the previous set of possible methods will be reused. - auth(session []byte, user string, p packetConn, rand io.Reader) (bool, []string, error) - - // method returns the RFC 4252 method name. - method() string -} - -// "none" authentication, RFC 4252 section 5.2. -type noneAuth int - -func (n *noneAuth) auth(session []byte, user string, c packetConn, rand io.Reader) (bool, []string, error) { - if err := c.writePacket(Marshal(&userAuthRequestMsg{ - User: user, - Service: serviceSSH, - Method: "none", - })); err != nil { - return false, nil, err - } - - return handleAuthResponse(c) -} - -func (n *noneAuth) method() string { - return "none" -} - -// passwordCallback is an AuthMethod that fetches the password through -// a function call, e.g. by prompting the user. -type passwordCallback func() (password string, err error) - -func (cb passwordCallback) auth(session []byte, user string, c packetConn, rand io.Reader) (bool, []string, error) { - type passwordAuthMsg struct { - User string `sshtype:"50"` - Service string - Method string - Reply bool - Password string - } - - pw, err := cb() - // REVIEW NOTE: is there a need to support skipping a password attempt? - // The program may only find out that the user doesn't have a password - // when prompting. - if err != nil { - return false, nil, err - } - - if err := c.writePacket(Marshal(&passwordAuthMsg{ - User: user, - Service: serviceSSH, - Method: cb.method(), - Reply: false, - Password: pw, - })); err != nil { - return false, nil, err - } - - return handleAuthResponse(c) -} - -func (cb passwordCallback) method() string { - return "password" -} - -// Password returns an AuthMethod using the given password. -func Password(secret string) AuthMethod { - return passwordCallback(func() (string, error) { return secret, nil }) -} - -// PasswordCallback returns an AuthMethod that uses a callback for -// fetching a password. -func PasswordCallback(prompt func() (secret string, err error)) AuthMethod { - return passwordCallback(prompt) -} - -type publickeyAuthMsg struct { - User string `sshtype:"50"` - Service string - Method string - // HasSig indicates to the receiver packet that the auth request is signed and - // should be used for authentication of the request. - HasSig bool - Algoname string - PubKey []byte - // Sig is tagged with "rest" so Marshal will exclude it during - // validateKey - Sig []byte `ssh:"rest"` -} - -// publicKeyCallback is an AuthMethod that uses a set of key -// pairs for authentication. -type publicKeyCallback func() ([]Signer, error) - -func (cb publicKeyCallback) method() string { - return "publickey" -} - -func (cb publicKeyCallback) auth(session []byte, user string, c packetConn, rand io.Reader) (bool, []string, error) { - // Authentication is performed in two stages. The first stage sends an - // enquiry to test if each key is acceptable to the remote. The second - // stage attempts to authenticate with the valid keys obtained in the - // first stage. - - signers, err := cb() - if err != nil { - return false, nil, err - } - var validKeys []Signer - for _, signer := range signers { - if ok, err := validateKey(signer.PublicKey(), user, c); ok { - validKeys = append(validKeys, signer) - } else { - if err != nil { - return false, nil, err - } - } - } - - // methods that may continue if this auth is not successful. - var methods []string - for _, signer := range validKeys { - pub := signer.PublicKey() - - pubKey := pub.Marshal() - sign, err := signer.Sign(rand, buildDataSignedForAuth(session, userAuthRequestMsg{ - User: user, - Service: serviceSSH, - Method: cb.method(), - }, []byte(pub.Type()), pubKey)) - if err != nil { - return false, nil, err - } - - // manually wrap the serialized signature in a string - s := Marshal(sign) - sig := make([]byte, stringLength(len(s))) - marshalString(sig, s) - msg := publickeyAuthMsg{ - User: user, - Service: serviceSSH, - Method: cb.method(), - HasSig: true, - Algoname: pub.Type(), - PubKey: pubKey, - Sig: sig, - } - p := Marshal(&msg) - if err := c.writePacket(p); err != nil { - return false, nil, err - } - var success bool - success, methods, err = handleAuthResponse(c) - if err != nil { - return false, nil, err - } - if success { - return success, methods, err - } - } - return false, methods, nil -} - -// validateKey validates the key provided is acceptable to the server. -func validateKey(key PublicKey, user string, c packetConn) (bool, error) { - pubKey := key.Marshal() - msg := publickeyAuthMsg{ - User: user, - Service: serviceSSH, - Method: "publickey", - HasSig: false, - Algoname: key.Type(), - PubKey: pubKey, - } - if err := c.writePacket(Marshal(&msg)); err != nil { - return false, err - } - - return confirmKeyAck(key, c) -} - -func confirmKeyAck(key PublicKey, c packetConn) (bool, error) { - pubKey := key.Marshal() - algoname := key.Type() - - for { - packet, err := c.readPacket() - if err != nil { - return false, err - } - switch packet[0] { - case msgUserAuthBanner: - // TODO(gpaul): add callback to present the banner to the user - case msgUserAuthPubKeyOk: - var msg userAuthPubKeyOkMsg - if err := Unmarshal(packet, &msg); err != nil { - return false, err - } - if msg.Algo != algoname || !bytes.Equal(msg.PubKey, pubKey) { - return false, nil - } - return true, nil - case msgUserAuthFailure: - return false, nil - default: - return false, unexpectedMessageError(msgUserAuthSuccess, packet[0]) - } - } -} - -// PublicKeys returns an AuthMethod that uses the given key -// pairs. -func PublicKeys(signers ...Signer) AuthMethod { - return publicKeyCallback(func() ([]Signer, error) { return signers, nil }) -} - -// PublicKeysCallback returns an AuthMethod that runs the given -// function to obtain a list of key pairs. -func PublicKeysCallback(getSigners func() (signers []Signer, err error)) AuthMethod { - return publicKeyCallback(getSigners) -} - -// handleAuthResponse returns whether the preceding authentication request succeeded -// along with a list of remaining authentication methods to try next and -// an error if an unexpected response was received. -func handleAuthResponse(c packetConn) (bool, []string, error) { - for { - packet, err := c.readPacket() - if err != nil { - return false, nil, err - } - - switch packet[0] { - case msgUserAuthBanner: - // TODO: add callback to present the banner to the user - case msgUserAuthFailure: - var msg userAuthFailureMsg - if err := Unmarshal(packet, &msg); err != nil { - return false, nil, err - } - return false, msg.Methods, nil - case msgUserAuthSuccess: - return true, nil, nil - default: - return false, nil, unexpectedMessageError(msgUserAuthSuccess, packet[0]) - } - } -} - -// KeyboardInteractiveChallenge should print questions, optionally -// disabling echoing (e.g. for passwords), and return all the answers. -// Challenge may be called multiple times in a single session. After -// successful authentication, the server may send a challenge with no -// questions, for which the user and instruction messages should be -// printed. RFC 4256 section 3.3 details how the UI should behave for -// both CLI and GUI environments. -type KeyboardInteractiveChallenge func(user, instruction string, questions []string, echos []bool) (answers []string, err error) - -// KeyboardInteractive returns a AuthMethod using a prompt/response -// sequence controlled by the server. -func KeyboardInteractive(challenge KeyboardInteractiveChallenge) AuthMethod { - return challenge -} - -func (cb KeyboardInteractiveChallenge) method() string { - return "keyboard-interactive" -} - -func (cb KeyboardInteractiveChallenge) auth(session []byte, user string, c packetConn, rand io.Reader) (bool, []string, error) { - type initiateMsg struct { - User string `sshtype:"50"` - Service string - Method string - Language string - Submethods string - } - - if err := c.writePacket(Marshal(&initiateMsg{ - User: user, - Service: serviceSSH, - Method: "keyboard-interactive", - })); err != nil { - return false, nil, err - } - - for { - packet, err := c.readPacket() - if err != nil { - return false, nil, err - } - - // like handleAuthResponse, but with less options. - switch packet[0] { - case msgUserAuthBanner: - // TODO: Print banners during userauth. - continue - case msgUserAuthInfoRequest: - // OK - case msgUserAuthFailure: - var msg userAuthFailureMsg - if err := Unmarshal(packet, &msg); err != nil { - return false, nil, err - } - return false, msg.Methods, nil - case msgUserAuthSuccess: - return true, nil, nil - default: - return false, nil, unexpectedMessageError(msgUserAuthInfoRequest, packet[0]) - } - - var msg userAuthInfoRequestMsg - if err := Unmarshal(packet, &msg); err != nil { - return false, nil, err - } - - // Manually unpack the prompt/echo pairs. - rest := msg.Prompts - var prompts []string - var echos []bool - for i := 0; i < int(msg.NumPrompts); i++ { - prompt, r, ok := parseString(rest) - if !ok || len(r) == 0 { - return false, nil, errors.New("ssh: prompt format error") - } - prompts = append(prompts, string(prompt)) - echos = append(echos, r[0] != 0) - rest = r[1:] - } - - if len(rest) != 0 { - return false, nil, errors.New("ssh: extra data following keyboard-interactive pairs") - } - - answers, err := cb(msg.User, msg.Instruction, prompts, echos) - if err != nil { - return false, nil, err - } - - if len(answers) != len(prompts) { - return false, nil, errors.New("ssh: not enough answers from keyboard-interactive callback") - } - responseLength := 1 + 4 - for _, a := range answers { - responseLength += stringLength(len(a)) - } - serialized := make([]byte, responseLength) - p := serialized - p[0] = msgUserAuthInfoResponse - p = p[1:] - p = marshalUint32(p, uint32(len(answers))) - for _, a := range answers { - p = marshalString(p, []byte(a)) - } - - if err := c.writePacket(serialized); err != nil { - return false, nil, err - } - } -} - -type retryableAuthMethod struct { - authMethod AuthMethod - maxTries int -} - -func (r *retryableAuthMethod) auth(session []byte, user string, c packetConn, rand io.Reader) (ok bool, methods []string, err error) { - for i := 0; r.maxTries <= 0 || i < r.maxTries; i++ { - ok, methods, err = r.authMethod.auth(session, user, c, rand) - if ok || err != nil { // either success or error terminate - return ok, methods, err - } - } - return ok, methods, err -} - -func (r *retryableAuthMethod) method() string { - return r.authMethod.method() -} - -// RetryableAuthMethod is a decorator for other auth methods enabling them to -// be retried up to maxTries before considering that AuthMethod itself failed. -// If maxTries is <= 0, will retry indefinitely -// -// This is useful for interactive clients using challenge/response type -// authentication (e.g. Keyboard-Interactive, Password, etc) where the user -// could mistype their response resulting in the server issuing a -// SSH_MSG_USERAUTH_FAILURE (rfc4252 #8 [password] and rfc4256 #3.4 -// [keyboard-interactive]); Without this decorator, the non-retryable -// AuthMethod would be removed from future consideration, and never tried again -// (and so the user would never be able to retry their entry). -func RetryableAuthMethod(auth AuthMethod, maxTries int) AuthMethod { - return &retryableAuthMethod{authMethod: auth, maxTries: maxTries} -} diff --git a/vendor/golang.org/x/crypto/ssh/common.go b/vendor/golang.org/x/crypto/ssh/common.go deleted file mode 100644 index 2c72ab5..0000000 --- a/vendor/golang.org/x/crypto/ssh/common.go +++ /dev/null @@ -1,356 +0,0 @@ -// Copyright 2011 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 ssh - -import ( - "crypto" - "crypto/rand" - "fmt" - "io" - "sync" - - _ "crypto/sha1" - _ "crypto/sha256" - _ "crypto/sha512" -) - -// These are string constants in the SSH protocol. -const ( - compressionNone = "none" - serviceUserAuth = "ssh-userauth" - serviceSSH = "ssh-connection" -) - -// supportedCiphers specifies the supported ciphers in preference order. -var supportedCiphers = []string{ - "aes128-ctr", "aes192-ctr", "aes256-ctr", - "aes128-gcm@openssh.com", - "arcfour256", "arcfour128", -} - -// supportedKexAlgos specifies the supported key-exchange algorithms in -// preference order. -var supportedKexAlgos = []string{ - kexAlgoCurve25519SHA256, - // P384 and P521 are not constant-time yet, but since we don't - // reuse ephemeral keys, using them for ECDH should be OK. - kexAlgoECDH256, kexAlgoECDH384, kexAlgoECDH521, - kexAlgoDH14SHA1, kexAlgoDH1SHA1, -} - -// supportedKexAlgos specifies the supported host-key algorithms (i.e. methods -// of authenticating servers) in preference order. -var supportedHostKeyAlgos = []string{ - CertAlgoRSAv01, CertAlgoDSAv01, CertAlgoECDSA256v01, - CertAlgoECDSA384v01, CertAlgoECDSA521v01, CertAlgoED25519v01, - - KeyAlgoECDSA256, KeyAlgoECDSA384, KeyAlgoECDSA521, - KeyAlgoRSA, KeyAlgoDSA, - - KeyAlgoED25519, -} - -// supportedMACs specifies a default set of MAC algorithms in preference order. -// This is based on RFC 4253, section 6.4, but with hmac-md5 variants removed -// because they have reached the end of their useful life. -var supportedMACs = []string{ - "hmac-sha2-256", "hmac-sha1", "hmac-sha1-96", -} - -var supportedCompressions = []string{compressionNone} - -// hashFuncs keeps the mapping of supported algorithms to their respective -// hashes needed for signature verification. -var hashFuncs = map[string]crypto.Hash{ - KeyAlgoRSA: crypto.SHA1, - KeyAlgoDSA: crypto.SHA1, - KeyAlgoECDSA256: crypto.SHA256, - KeyAlgoECDSA384: crypto.SHA384, - KeyAlgoECDSA521: crypto.SHA512, - CertAlgoRSAv01: crypto.SHA1, - CertAlgoDSAv01: crypto.SHA1, - CertAlgoECDSA256v01: crypto.SHA256, - CertAlgoECDSA384v01: crypto.SHA384, - CertAlgoECDSA521v01: crypto.SHA512, -} - -// unexpectedMessageError results when the SSH message that we received didn't -// match what we wanted. -func unexpectedMessageError(expected, got uint8) error { - return fmt.Errorf("ssh: unexpected message type %d (expected %d)", got, expected) -} - -// parseError results from a malformed SSH message. -func parseError(tag uint8) error { - return fmt.Errorf("ssh: parse error in message type %d", tag) -} - -func findCommon(what string, client []string, server []string) (common string, err error) { - for _, c := range client { - for _, s := range server { - if c == s { - return c, nil - } - } - } - return "", fmt.Errorf("ssh: no common algorithm for %s; client offered: %v, server offered: %v", what, client, server) -} - -type directionAlgorithms struct { - Cipher string - MAC string - Compression string -} - -type algorithms struct { - kex string - hostKey string - w directionAlgorithms - r directionAlgorithms -} - -func findAgreedAlgorithms(clientKexInit, serverKexInit *kexInitMsg) (algs *algorithms, err error) { - result := &algorithms{} - - result.kex, err = findCommon("key exchange", clientKexInit.KexAlgos, serverKexInit.KexAlgos) - if err != nil { - return - } - - result.hostKey, err = findCommon("host key", clientKexInit.ServerHostKeyAlgos, serverKexInit.ServerHostKeyAlgos) - if err != nil { - return - } - - result.w.Cipher, err = findCommon("client to server cipher", clientKexInit.CiphersClientServer, serverKexInit.CiphersClientServer) - if err != nil { - return - } - - result.r.Cipher, err = findCommon("server to client cipher", clientKexInit.CiphersServerClient, serverKexInit.CiphersServerClient) - if err != nil { - return - } - - result.w.MAC, err = findCommon("client to server MAC", clientKexInit.MACsClientServer, serverKexInit.MACsClientServer) - if err != nil { - return - } - - result.r.MAC, err = findCommon("server to client MAC", clientKexInit.MACsServerClient, serverKexInit.MACsServerClient) - if err != nil { - return - } - - result.w.Compression, err = findCommon("client to server compression", clientKexInit.CompressionClientServer, serverKexInit.CompressionClientServer) - if err != nil { - return - } - - result.r.Compression, err = findCommon("server to client compression", clientKexInit.CompressionServerClient, serverKexInit.CompressionServerClient) - if err != nil { - return - } - - return result, nil -} - -// If rekeythreshold is too small, we can't make any progress sending -// stuff. -const minRekeyThreshold uint64 = 256 - -// Config contains configuration data common to both ServerConfig and -// ClientConfig. -type Config struct { - // Rand provides the source of entropy for cryptographic - // primitives. If Rand is nil, the cryptographic random reader - // in package crypto/rand will be used. - Rand io.Reader - - // The maximum number of bytes sent or received after which a - // new key is negotiated. It must be at least 256. If - // unspecified, 1 gigabyte is used. - RekeyThreshold uint64 - - // The allowed key exchanges algorithms. If unspecified then a - // default set of algorithms is used. - KeyExchanges []string - - // The allowed cipher algorithms. If unspecified then a sensible - // default is used. - Ciphers []string - - // The allowed MAC algorithms. If unspecified then a sensible default - // is used. - MACs []string -} - -// SetDefaults sets sensible values for unset fields in config. This is -// exported for testing: Configs passed to SSH functions are copied and have -// default values set automatically. -func (c *Config) SetDefaults() { - if c.Rand == nil { - c.Rand = rand.Reader - } - if c.Ciphers == nil { - c.Ciphers = supportedCiphers - } - var ciphers []string - for _, c := range c.Ciphers { - if cipherModes[c] != nil { - // reject the cipher if we have no cipherModes definition - ciphers = append(ciphers, c) - } - } - c.Ciphers = ciphers - - if c.KeyExchanges == nil { - c.KeyExchanges = supportedKexAlgos - } - - if c.MACs == nil { - c.MACs = supportedMACs - } - - if c.RekeyThreshold == 0 { - // RFC 4253, section 9 suggests rekeying after 1G. - c.RekeyThreshold = 1 << 30 - } - if c.RekeyThreshold < minRekeyThreshold { - c.RekeyThreshold = minRekeyThreshold - } -} - -// buildDataSignedForAuth returns the data that is signed in order to prove -// possession of a private key. See RFC 4252, section 7. -func buildDataSignedForAuth(sessionId []byte, req userAuthRequestMsg, algo, pubKey []byte) []byte { - data := struct { - Session []byte - Type byte - User string - Service string - Method string - Sign bool - Algo []byte - PubKey []byte - }{ - sessionId, - msgUserAuthRequest, - req.User, - req.Service, - req.Method, - true, - algo, - pubKey, - } - return Marshal(data) -} - -func appendU16(buf []byte, n uint16) []byte { - return append(buf, byte(n>>8), byte(n)) -} - -func appendU32(buf []byte, n uint32) []byte { - return append(buf, byte(n>>24), byte(n>>16), byte(n>>8), byte(n)) -} - -func appendU64(buf []byte, n uint64) []byte { - return append(buf, - byte(n>>56), byte(n>>48), byte(n>>40), byte(n>>32), - byte(n>>24), byte(n>>16), byte(n>>8), byte(n)) -} - -func appendInt(buf []byte, n int) []byte { - return appendU32(buf, uint32(n)) -} - -func appendString(buf []byte, s string) []byte { - buf = appendU32(buf, uint32(len(s))) - buf = append(buf, s...) - return buf -} - -func appendBool(buf []byte, b bool) []byte { - if b { - return append(buf, 1) - } - return append(buf, 0) -} - -// newCond is a helper to hide the fact that there is no usable zero -// value for sync.Cond. -func newCond() *sync.Cond { return sync.NewCond(new(sync.Mutex)) } - -// window represents the buffer available to clients -// wishing to write to a channel. -type window struct { - *sync.Cond - win uint32 // RFC 4254 5.2 says the window size can grow to 2^32-1 - writeWaiters int - closed bool -} - -// add adds win to the amount of window available -// for consumers. -func (w *window) add(win uint32) bool { - // a zero sized window adjust is a noop. - if win == 0 { - return true - } - w.L.Lock() - if w.win+win < win { - w.L.Unlock() - return false - } - w.win += win - // It is unusual that multiple goroutines would be attempting to reserve - // window space, but not guaranteed. Use broadcast to notify all waiters - // that additional window is available. - w.Broadcast() - w.L.Unlock() - return true -} - -// close sets the window to closed, so all reservations fail -// immediately. -func (w *window) close() { - w.L.Lock() - w.closed = true - w.Broadcast() - w.L.Unlock() -} - -// reserve reserves win from the available window capacity. -// If no capacity remains, reserve will block. reserve may -// return less than requested. -func (w *window) reserve(win uint32) (uint32, error) { - var err error - w.L.Lock() - w.writeWaiters++ - w.Broadcast() - for w.win == 0 && !w.closed { - w.Wait() - } - w.writeWaiters-- - if w.win < win { - win = w.win - } - w.win -= win - if w.closed { - err = io.EOF - } - w.L.Unlock() - return win, err -} - -// waitWriterBlocked waits until some goroutine is blocked for further -// writes. It is used in tests only. -func (w *window) waitWriterBlocked() { - w.Cond.L.Lock() - for w.writeWaiters == 0 { - w.Cond.Wait() - } - w.Cond.L.Unlock() -} diff --git a/vendor/golang.org/x/crypto/ssh/connection.go b/vendor/golang.org/x/crypto/ssh/connection.go deleted file mode 100644 index e786f2f..0000000 --- a/vendor/golang.org/x/crypto/ssh/connection.go +++ /dev/null @@ -1,143 +0,0 @@ -// Copyright 2013 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 ssh - -import ( - "fmt" - "net" -) - -// OpenChannelError is returned if the other side rejects an -// OpenChannel request. -type OpenChannelError struct { - Reason RejectionReason - Message string -} - -func (e *OpenChannelError) Error() string { - return fmt.Sprintf("ssh: rejected: %s (%s)", e.Reason, e.Message) -} - -// ConnMetadata holds metadata for the connection. -type ConnMetadata interface { - // User returns the user ID for this connection. - User() string - - // SessionID returns the sesson hash, also denoted by H. - SessionID() []byte - - // ClientVersion returns the client's version string as hashed - // into the session ID. - ClientVersion() []byte - - // ServerVersion returns the server's version string as hashed - // into the session ID. - ServerVersion() []byte - - // RemoteAddr returns the remote address for this connection. - RemoteAddr() net.Addr - - // LocalAddr returns the local address for this connection. - LocalAddr() net.Addr -} - -// Conn represents an SSH connection for both server and client roles. -// Conn is the basis for implementing an application layer, such -// as ClientConn, which implements the traditional shell access for -// clients. -type Conn interface { - ConnMetadata - - // SendRequest sends a global request, and returns the - // reply. If wantReply is true, it returns the response status - // and payload. See also RFC4254, section 4. - SendRequest(name string, wantReply bool, payload []byte) (bool, []byte, error) - - // OpenChannel tries to open an channel. If the request is - // rejected, it returns *OpenChannelError. On success it returns - // the SSH Channel and a Go channel for incoming, out-of-band - // requests. The Go channel must be serviced, or the - // connection will hang. - OpenChannel(name string, data []byte) (Channel, <-chan *Request, error) - - // Close closes the underlying network connection - Close() error - - // Wait blocks until the connection has shut down, and returns the - // error causing the shutdown. - Wait() error - - // TODO(hanwen): consider exposing: - // RequestKeyChange - // Disconnect -} - -// DiscardRequests consumes and rejects all requests from the -// passed-in channel. -func DiscardRequests(in <-chan *Request) { - for req := range in { - if req.WantReply { - req.Reply(false, nil) - } - } -} - -// A connection represents an incoming connection. -type connection struct { - transport *handshakeTransport - sshConn - - // The connection protocol. - *mux -} - -func (c *connection) Close() error { - return c.sshConn.conn.Close() -} - -// sshconn provides net.Conn metadata, but disallows direct reads and -// writes. -type sshConn struct { - conn net.Conn - - user string - sessionID []byte - clientVersion []byte - serverVersion []byte -} - -func dup(src []byte) []byte { - dst := make([]byte, len(src)) - copy(dst, src) - return dst -} - -func (c *sshConn) User() string { - return c.user -} - -func (c *sshConn) RemoteAddr() net.Addr { - return c.conn.RemoteAddr() -} - -func (c *sshConn) Close() error { - return c.conn.Close() -} - -func (c *sshConn) LocalAddr() net.Addr { - return c.conn.LocalAddr() -} - -func (c *sshConn) SessionID() []byte { - return dup(c.sessionID) -} - -func (c *sshConn) ClientVersion() []byte { - return dup(c.clientVersion) -} - -func (c *sshConn) ServerVersion() []byte { - return dup(c.serverVersion) -} diff --git a/vendor/golang.org/x/crypto/ssh/doc.go b/vendor/golang.org/x/crypto/ssh/doc.go deleted file mode 100644 index d6be894..0000000 --- a/vendor/golang.org/x/crypto/ssh/doc.go +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright 2011 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 ssh implements an SSH client and server. - -SSH is a transport security protocol, an authentication protocol and a -family of application protocols. The most typical application level -protocol is a remote shell and this is specifically implemented. However, -the multiplexed nature of SSH is exposed to users that wish to support -others. - -References: - [PROTOCOL.certkeys]: http://cvsweb.openbsd.org/cgi-bin/cvsweb/src/usr.bin/ssh/PROTOCOL.certkeys?rev=HEAD - [SSH-PARAMETERS]: http://www.iana.org/assignments/ssh-parameters/ssh-parameters.xml#ssh-parameters-1 -*/ -package ssh // import "golang.org/x/crypto/ssh" diff --git a/vendor/golang.org/x/crypto/ssh/handshake.go b/vendor/golang.org/x/crypto/ssh/handshake.go deleted file mode 100644 index 37d42e4..0000000 --- a/vendor/golang.org/x/crypto/ssh/handshake.go +++ /dev/null @@ -1,460 +0,0 @@ -// Copyright 2013 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 ssh - -import ( - "crypto/rand" - "errors" - "fmt" - "io" - "log" - "net" - "sync" -) - -// debugHandshake, if set, prints messages sent and received. Key -// exchange messages are printed as if DH were used, so the debug -// messages are wrong when using ECDH. -const debugHandshake = false - -// keyingTransport is a packet based transport that supports key -// changes. It need not be thread-safe. It should pass through -// msgNewKeys in both directions. -type keyingTransport interface { - packetConn - - // prepareKeyChange sets up a key change. The key change for a - // direction will be effected if a msgNewKeys message is sent - // or received. - prepareKeyChange(*algorithms, *kexResult) error -} - -// handshakeTransport implements rekeying on top of a keyingTransport -// and offers a thread-safe writePacket() interface. -type handshakeTransport struct { - conn keyingTransport - config *Config - - serverVersion []byte - clientVersion []byte - - // hostKeys is non-empty if we are the server. In that case, - // it contains all host keys that can be used to sign the - // connection. - hostKeys []Signer - - // hostKeyAlgorithms is non-empty if we are the client. In that case, - // we accept these key types from the server as host key. - hostKeyAlgorithms []string - - // On read error, incoming is closed, and readError is set. - incoming chan []byte - readError error - - // data for host key checking - hostKeyCallback func(hostname string, remote net.Addr, key PublicKey) error - dialAddress string - remoteAddr net.Addr - - readSinceKex uint64 - - // Protects the writing side of the connection - mu sync.Mutex - cond *sync.Cond - sentInitPacket []byte - sentInitMsg *kexInitMsg - writtenSinceKex uint64 - writeError error - - // The session ID or nil if first kex did not complete yet. - sessionID []byte -} - -func newHandshakeTransport(conn keyingTransport, config *Config, clientVersion, serverVersion []byte) *handshakeTransport { - t := &handshakeTransport{ - conn: conn, - serverVersion: serverVersion, - clientVersion: clientVersion, - incoming: make(chan []byte, 16), - config: config, - } - t.cond = sync.NewCond(&t.mu) - return t -} - -func newClientTransport(conn keyingTransport, clientVersion, serverVersion []byte, config *ClientConfig, dialAddr string, addr net.Addr) *handshakeTransport { - t := newHandshakeTransport(conn, &config.Config, clientVersion, serverVersion) - t.dialAddress = dialAddr - t.remoteAddr = addr - t.hostKeyCallback = config.HostKeyCallback - if config.HostKeyAlgorithms != nil { - t.hostKeyAlgorithms = config.HostKeyAlgorithms - } else { - t.hostKeyAlgorithms = supportedHostKeyAlgos - } - go t.readLoop() - return t -} - -func newServerTransport(conn keyingTransport, clientVersion, serverVersion []byte, config *ServerConfig) *handshakeTransport { - t := newHandshakeTransport(conn, &config.Config, clientVersion, serverVersion) - t.hostKeys = config.hostKeys - go t.readLoop() - return t -} - -func (t *handshakeTransport) getSessionID() []byte { - return t.sessionID -} - -func (t *handshakeTransport) id() string { - if len(t.hostKeys) > 0 { - return "server" - } - return "client" -} - -func (t *handshakeTransport) readPacket() ([]byte, error) { - p, ok := <-t.incoming - if !ok { - return nil, t.readError - } - return p, nil -} - -func (t *handshakeTransport) readLoop() { - for { - p, err := t.readOnePacket() - if err != nil { - t.readError = err - close(t.incoming) - break - } - if p[0] == msgIgnore || p[0] == msgDebug { - continue - } - t.incoming <- p - } - - // If we can't read, declare the writing part dead too. - t.mu.Lock() - defer t.mu.Unlock() - if t.writeError == nil { - t.writeError = t.readError - } - t.cond.Broadcast() -} - -func (t *handshakeTransport) readOnePacket() ([]byte, error) { - if t.readSinceKex > t.config.RekeyThreshold { - if err := t.requestKeyChange(); err != nil { - return nil, err - } - } - - p, err := t.conn.readPacket() - if err != nil { - return nil, err - } - - t.readSinceKex += uint64(len(p)) - if debugHandshake { - if p[0] == msgChannelData || p[0] == msgChannelExtendedData { - log.Printf("%s got data (packet %d bytes)", t.id(), len(p)) - } else { - msg, err := decode(p) - log.Printf("%s got %T %v (%v)", t.id(), msg, msg, err) - } - } - if p[0] != msgKexInit { - return p, nil - } - - t.mu.Lock() - - firstKex := t.sessionID == nil - - err = t.enterKeyExchangeLocked(p) - if err != nil { - // drop connection - t.conn.Close() - t.writeError = err - } - - if debugHandshake { - log.Printf("%s exited key exchange (first %v), err %v", t.id(), firstKex, err) - } - - // Unblock writers. - t.sentInitMsg = nil - t.sentInitPacket = nil - t.cond.Broadcast() - t.writtenSinceKex = 0 - t.mu.Unlock() - - if err != nil { - return nil, err - } - - t.readSinceKex = 0 - - // By default, a key exchange is hidden from higher layers by - // translating it into msgIgnore. - successPacket := []byte{msgIgnore} - if firstKex { - // sendKexInit() for the first kex waits for - // msgNewKeys so the authentication process is - // guaranteed to happen over an encrypted transport. - successPacket = []byte{msgNewKeys} - } - - return successPacket, nil -} - -// keyChangeCategory describes whether a key exchange is the first on a -// connection, or a subsequent one. -type keyChangeCategory bool - -const ( - firstKeyExchange keyChangeCategory = true - subsequentKeyExchange keyChangeCategory = false -) - -// sendKexInit sends a key change message, and returns the message -// that was sent. After initiating the key change, all writes will be -// blocked until the change is done, and a failed key change will -// close the underlying transport. This function is safe for -// concurrent use by multiple goroutines. -func (t *handshakeTransport) sendKexInit(isFirst keyChangeCategory) error { - var err error - - t.mu.Lock() - // If this is the initial key change, but we already have a sessionID, - // then do nothing because the key exchange has already completed - // asynchronously. - if !isFirst || t.sessionID == nil { - _, _, err = t.sendKexInitLocked(isFirst) - } - t.mu.Unlock() - if err != nil { - return err - } - if isFirst { - if packet, err := t.readPacket(); err != nil { - return err - } else if packet[0] != msgNewKeys { - return unexpectedMessageError(msgNewKeys, packet[0]) - } - } - return nil -} - -func (t *handshakeTransport) requestInitialKeyChange() error { - return t.sendKexInit(firstKeyExchange) -} - -func (t *handshakeTransport) requestKeyChange() error { - return t.sendKexInit(subsequentKeyExchange) -} - -// sendKexInitLocked sends a key change message. t.mu must be locked -// while this happens. -func (t *handshakeTransport) sendKexInitLocked(isFirst keyChangeCategory) (*kexInitMsg, []byte, error) { - // kexInits may be sent either in response to the other side, - // or because our side wants to initiate a key change, so we - // may have already sent a kexInit. In that case, don't send a - // second kexInit. - if t.sentInitMsg != nil { - return t.sentInitMsg, t.sentInitPacket, nil - } - - msg := &kexInitMsg{ - KexAlgos: t.config.KeyExchanges, - CiphersClientServer: t.config.Ciphers, - CiphersServerClient: t.config.Ciphers, - MACsClientServer: t.config.MACs, - MACsServerClient: t.config.MACs, - CompressionClientServer: supportedCompressions, - CompressionServerClient: supportedCompressions, - } - io.ReadFull(rand.Reader, msg.Cookie[:]) - - if len(t.hostKeys) > 0 { - for _, k := range t.hostKeys { - msg.ServerHostKeyAlgos = append( - msg.ServerHostKeyAlgos, k.PublicKey().Type()) - } - } else { - msg.ServerHostKeyAlgos = t.hostKeyAlgorithms - } - packet := Marshal(msg) - - // writePacket destroys the contents, so save a copy. - packetCopy := make([]byte, len(packet)) - copy(packetCopy, packet) - - if err := t.conn.writePacket(packetCopy); err != nil { - return nil, nil, err - } - - t.sentInitMsg = msg - t.sentInitPacket = packet - return msg, packet, nil -} - -func (t *handshakeTransport) writePacket(p []byte) error { - t.mu.Lock() - defer t.mu.Unlock() - - if t.writtenSinceKex > t.config.RekeyThreshold { - t.sendKexInitLocked(subsequentKeyExchange) - } - for t.sentInitMsg != nil && t.writeError == nil { - t.cond.Wait() - } - if t.writeError != nil { - return t.writeError - } - t.writtenSinceKex += uint64(len(p)) - - switch p[0] { - case msgKexInit: - return errors.New("ssh: only handshakeTransport can send kexInit") - case msgNewKeys: - return errors.New("ssh: only handshakeTransport can send newKeys") - default: - return t.conn.writePacket(p) - } -} - -func (t *handshakeTransport) Close() error { - return t.conn.Close() -} - -// enterKeyExchange runs the key exchange. t.mu must be held while running this. -func (t *handshakeTransport) enterKeyExchangeLocked(otherInitPacket []byte) error { - if debugHandshake { - log.Printf("%s entered key exchange", t.id()) - } - myInit, myInitPacket, err := t.sendKexInitLocked(subsequentKeyExchange) - if err != nil { - return err - } - - otherInit := &kexInitMsg{} - if err := Unmarshal(otherInitPacket, otherInit); err != nil { - return err - } - - magics := handshakeMagics{ - clientVersion: t.clientVersion, - serverVersion: t.serverVersion, - clientKexInit: otherInitPacket, - serverKexInit: myInitPacket, - } - - clientInit := otherInit - serverInit := myInit - if len(t.hostKeys) == 0 { - clientInit = myInit - serverInit = otherInit - - magics.clientKexInit = myInitPacket - magics.serverKexInit = otherInitPacket - } - - algs, err := findAgreedAlgorithms(clientInit, serverInit) - if err != nil { - return err - } - - // We don't send FirstKexFollows, but we handle receiving it. - // - // RFC 4253 section 7 defines the kex and the agreement method for - // first_kex_packet_follows. It states that the guessed packet - // should be ignored if the "kex algorithm and/or the host - // key algorithm is guessed wrong (server and client have - // different preferred algorithm), or if any of the other - // algorithms cannot be agreed upon". The other algorithms have - // already been checked above so the kex algorithm and host key - // algorithm are checked here. - if otherInit.FirstKexFollows && (clientInit.KexAlgos[0] != serverInit.KexAlgos[0] || clientInit.ServerHostKeyAlgos[0] != serverInit.ServerHostKeyAlgos[0]) { - // other side sent a kex message for the wrong algorithm, - // which we have to ignore. - if _, err := t.conn.readPacket(); err != nil { - return err - } - } - - kex, ok := kexAlgoMap[algs.kex] - if !ok { - return fmt.Errorf("ssh: unexpected key exchange algorithm %v", algs.kex) - } - - var result *kexResult - if len(t.hostKeys) > 0 { - result, err = t.server(kex, algs, &magics) - } else { - result, err = t.client(kex, algs, &magics) - } - - if err != nil { - return err - } - - if t.sessionID == nil { - t.sessionID = result.H - } - result.SessionID = t.sessionID - - t.conn.prepareKeyChange(algs, result) - if err = t.conn.writePacket([]byte{msgNewKeys}); err != nil { - return err - } - if packet, err := t.conn.readPacket(); err != nil { - return err - } else if packet[0] != msgNewKeys { - return unexpectedMessageError(msgNewKeys, packet[0]) - } - - return nil -} - -func (t *handshakeTransport) server(kex kexAlgorithm, algs *algorithms, magics *handshakeMagics) (*kexResult, error) { - var hostKey Signer - for _, k := range t.hostKeys { - if algs.hostKey == k.PublicKey().Type() { - hostKey = k - } - } - - r, err := kex.Server(t.conn, t.config.Rand, magics, hostKey) - return r, err -} - -func (t *handshakeTransport) client(kex kexAlgorithm, algs *algorithms, magics *handshakeMagics) (*kexResult, error) { - result, err := kex.Client(t.conn, t.config.Rand, magics) - if err != nil { - return nil, err - } - - hostKey, err := ParsePublicKey(result.HostKey) - if err != nil { - return nil, err - } - - if err := verifyHostKeySignature(hostKey, result); err != nil { - return nil, err - } - - if t.hostKeyCallback != nil { - err = t.hostKeyCallback(t.dialAddress, t.remoteAddr, hostKey) - if err != nil { - return nil, err - } - } - - return result, nil -} diff --git a/vendor/golang.org/x/crypto/ssh/kex.go b/vendor/golang.org/x/crypto/ssh/kex.go deleted file mode 100644 index c87fbeb..0000000 --- a/vendor/golang.org/x/crypto/ssh/kex.go +++ /dev/null @@ -1,540 +0,0 @@ -// Copyright 2013 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 ssh - -import ( - "crypto" - "crypto/ecdsa" - "crypto/elliptic" - "crypto/rand" - "crypto/subtle" - "errors" - "io" - "math/big" - - "golang.org/x/crypto/curve25519" -) - -const ( - kexAlgoDH1SHA1 = "diffie-hellman-group1-sha1" - kexAlgoDH14SHA1 = "diffie-hellman-group14-sha1" - kexAlgoECDH256 = "ecdh-sha2-nistp256" - kexAlgoECDH384 = "ecdh-sha2-nistp384" - kexAlgoECDH521 = "ecdh-sha2-nistp521" - kexAlgoCurve25519SHA256 = "curve25519-sha256@libssh.org" -) - -// kexResult captures the outcome of a key exchange. -type kexResult struct { - // Session hash. See also RFC 4253, section 8. - H []byte - - // Shared secret. See also RFC 4253, section 8. - K []byte - - // Host key as hashed into H. - HostKey []byte - - // Signature of H. - Signature []byte - - // A cryptographic hash function that matches the security - // level of the key exchange algorithm. It is used for - // calculating H, and for deriving keys from H and K. - Hash crypto.Hash - - // The session ID, which is the first H computed. This is used - // to derive key material inside the transport. - SessionID []byte -} - -// handshakeMagics contains data that is always included in the -// session hash. -type handshakeMagics struct { - clientVersion, serverVersion []byte - clientKexInit, serverKexInit []byte -} - -func (m *handshakeMagics) write(w io.Writer) { - writeString(w, m.clientVersion) - writeString(w, m.serverVersion) - writeString(w, m.clientKexInit) - writeString(w, m.serverKexInit) -} - -// kexAlgorithm abstracts different key exchange algorithms. -type kexAlgorithm interface { - // Server runs server-side key agreement, signing the result - // with a hostkey. - Server(p packetConn, rand io.Reader, magics *handshakeMagics, s Signer) (*kexResult, error) - - // Client runs the client-side key agreement. Caller is - // responsible for verifying the host key signature. - Client(p packetConn, rand io.Reader, magics *handshakeMagics) (*kexResult, error) -} - -// dhGroup is a multiplicative group suitable for implementing Diffie-Hellman key agreement. -type dhGroup struct { - g, p, pMinus1 *big.Int -} - -func (group *dhGroup) diffieHellman(theirPublic, myPrivate *big.Int) (*big.Int, error) { - if theirPublic.Cmp(bigOne) <= 0 || theirPublic.Cmp(group.pMinus1) >= 0 { - return nil, errors.New("ssh: DH parameter out of bounds") - } - return new(big.Int).Exp(theirPublic, myPrivate, group.p), nil -} - -func (group *dhGroup) Client(c packetConn, randSource io.Reader, magics *handshakeMagics) (*kexResult, error) { - hashFunc := crypto.SHA1 - - var x *big.Int - for { - var err error - if x, err = rand.Int(randSource, group.pMinus1); err != nil { - return nil, err - } - if x.Sign() > 0 { - break - } - } - - X := new(big.Int).Exp(group.g, x, group.p) - kexDHInit := kexDHInitMsg{ - X: X, - } - if err := c.writePacket(Marshal(&kexDHInit)); err != nil { - return nil, err - } - - packet, err := c.readPacket() - if err != nil { - return nil, err - } - - var kexDHReply kexDHReplyMsg - if err = Unmarshal(packet, &kexDHReply); err != nil { - return nil, err - } - - kInt, err := group.diffieHellman(kexDHReply.Y, x) - if err != nil { - return nil, err - } - - h := hashFunc.New() - magics.write(h) - writeString(h, kexDHReply.HostKey) - writeInt(h, X) - writeInt(h, kexDHReply.Y) - K := make([]byte, intLength(kInt)) - marshalInt(K, kInt) - h.Write(K) - - return &kexResult{ - H: h.Sum(nil), - K: K, - HostKey: kexDHReply.HostKey, - Signature: kexDHReply.Signature, - Hash: crypto.SHA1, - }, nil -} - -func (group *dhGroup) Server(c packetConn, randSource io.Reader, magics *handshakeMagics, priv Signer) (result *kexResult, err error) { - hashFunc := crypto.SHA1 - packet, err := c.readPacket() - if err != nil { - return - } - var kexDHInit kexDHInitMsg - if err = Unmarshal(packet, &kexDHInit); err != nil { - return - } - - var y *big.Int - for { - if y, err = rand.Int(randSource, group.pMinus1); err != nil { - return - } - if y.Sign() > 0 { - break - } - } - - Y := new(big.Int).Exp(group.g, y, group.p) - kInt, err := group.diffieHellman(kexDHInit.X, y) - if err != nil { - return nil, err - } - - hostKeyBytes := priv.PublicKey().Marshal() - - h := hashFunc.New() - magics.write(h) - writeString(h, hostKeyBytes) - writeInt(h, kexDHInit.X) - writeInt(h, Y) - - K := make([]byte, intLength(kInt)) - marshalInt(K, kInt) - h.Write(K) - - H := h.Sum(nil) - - // H is already a hash, but the hostkey signing will apply its - // own key-specific hash algorithm. - sig, err := signAndMarshal(priv, randSource, H) - if err != nil { - return nil, err - } - - kexDHReply := kexDHReplyMsg{ - HostKey: hostKeyBytes, - Y: Y, - Signature: sig, - } - packet = Marshal(&kexDHReply) - - err = c.writePacket(packet) - return &kexResult{ - H: H, - K: K, - HostKey: hostKeyBytes, - Signature: sig, - Hash: crypto.SHA1, - }, nil -} - -// ecdh performs Elliptic Curve Diffie-Hellman key exchange as -// described in RFC 5656, section 4. -type ecdh struct { - curve elliptic.Curve -} - -func (kex *ecdh) Client(c packetConn, rand io.Reader, magics *handshakeMagics) (*kexResult, error) { - ephKey, err := ecdsa.GenerateKey(kex.curve, rand) - if err != nil { - return nil, err - } - - kexInit := kexECDHInitMsg{ - ClientPubKey: elliptic.Marshal(kex.curve, ephKey.PublicKey.X, ephKey.PublicKey.Y), - } - - serialized := Marshal(&kexInit) - if err := c.writePacket(serialized); err != nil { - return nil, err - } - - packet, err := c.readPacket() - if err != nil { - return nil, err - } - - var reply kexECDHReplyMsg - if err = Unmarshal(packet, &reply); err != nil { - return nil, err - } - - x, y, err := unmarshalECKey(kex.curve, reply.EphemeralPubKey) - if err != nil { - return nil, err - } - - // generate shared secret - secret, _ := kex.curve.ScalarMult(x, y, ephKey.D.Bytes()) - - h := ecHash(kex.curve).New() - magics.write(h) - writeString(h, reply.HostKey) - writeString(h, kexInit.ClientPubKey) - writeString(h, reply.EphemeralPubKey) - K := make([]byte, intLength(secret)) - marshalInt(K, secret) - h.Write(K) - - return &kexResult{ - H: h.Sum(nil), - K: K, - HostKey: reply.HostKey, - Signature: reply.Signature, - Hash: ecHash(kex.curve), - }, nil -} - -// unmarshalECKey parses and checks an EC key. -func unmarshalECKey(curve elliptic.Curve, pubkey []byte) (x, y *big.Int, err error) { - x, y = elliptic.Unmarshal(curve, pubkey) - if x == nil { - return nil, nil, errors.New("ssh: elliptic.Unmarshal failure") - } - if !validateECPublicKey(curve, x, y) { - return nil, nil, errors.New("ssh: public key not on curve") - } - return x, y, nil -} - -// validateECPublicKey checks that the point is a valid public key for -// the given curve. See [SEC1], 3.2.2 -func validateECPublicKey(curve elliptic.Curve, x, y *big.Int) bool { - if x.Sign() == 0 && y.Sign() == 0 { - return false - } - - if x.Cmp(curve.Params().P) >= 0 { - return false - } - - if y.Cmp(curve.Params().P) >= 0 { - return false - } - - if !curve.IsOnCurve(x, y) { - return false - } - - // We don't check if N * PubKey == 0, since - // - // - the NIST curves have cofactor = 1, so this is implicit. - // (We don't foresee an implementation that supports non NIST - // curves) - // - // - for ephemeral keys, we don't need to worry about small - // subgroup attacks. - return true -} - -func (kex *ecdh) Server(c packetConn, rand io.Reader, magics *handshakeMagics, priv Signer) (result *kexResult, err error) { - packet, err := c.readPacket() - if err != nil { - return nil, err - } - - var kexECDHInit kexECDHInitMsg - if err = Unmarshal(packet, &kexECDHInit); err != nil { - return nil, err - } - - clientX, clientY, err := unmarshalECKey(kex.curve, kexECDHInit.ClientPubKey) - if err != nil { - return nil, err - } - - // We could cache this key across multiple users/multiple - // connection attempts, but the benefit is small. OpenSSH - // generates a new key for each incoming connection. - ephKey, err := ecdsa.GenerateKey(kex.curve, rand) - if err != nil { - return nil, err - } - - hostKeyBytes := priv.PublicKey().Marshal() - - serializedEphKey := elliptic.Marshal(kex.curve, ephKey.PublicKey.X, ephKey.PublicKey.Y) - - // generate shared secret - secret, _ := kex.curve.ScalarMult(clientX, clientY, ephKey.D.Bytes()) - - h := ecHash(kex.curve).New() - magics.write(h) - writeString(h, hostKeyBytes) - writeString(h, kexECDHInit.ClientPubKey) - writeString(h, serializedEphKey) - - K := make([]byte, intLength(secret)) - marshalInt(K, secret) - h.Write(K) - - H := h.Sum(nil) - - // H is already a hash, but the hostkey signing will apply its - // own key-specific hash algorithm. - sig, err := signAndMarshal(priv, rand, H) - if err != nil { - return nil, err - } - - reply := kexECDHReplyMsg{ - EphemeralPubKey: serializedEphKey, - HostKey: hostKeyBytes, - Signature: sig, - } - - serialized := Marshal(&reply) - if err := c.writePacket(serialized); err != nil { - return nil, err - } - - return &kexResult{ - H: H, - K: K, - HostKey: reply.HostKey, - Signature: sig, - Hash: ecHash(kex.curve), - }, nil -} - -var kexAlgoMap = map[string]kexAlgorithm{} - -func init() { - // This is the group called diffie-hellman-group1-sha1 in RFC - // 4253 and Oakley Group 2 in RFC 2409. - p, _ := new(big.Int).SetString("FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381FFFFFFFFFFFFFFFF", 16) - kexAlgoMap[kexAlgoDH1SHA1] = &dhGroup{ - g: new(big.Int).SetInt64(2), - p: p, - pMinus1: new(big.Int).Sub(p, bigOne), - } - - // This is the group called diffie-hellman-group14-sha1 in RFC - // 4253 and Oakley Group 14 in RFC 3526. - p, _ = new(big.Int).SetString("FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF6955817183995497CEA956AE515D2261898FA051015728E5A8AACAA68FFFFFFFFFFFFFFFF", 16) - - kexAlgoMap[kexAlgoDH14SHA1] = &dhGroup{ - g: new(big.Int).SetInt64(2), - p: p, - pMinus1: new(big.Int).Sub(p, bigOne), - } - - kexAlgoMap[kexAlgoECDH521] = &ecdh{elliptic.P521()} - kexAlgoMap[kexAlgoECDH384] = &ecdh{elliptic.P384()} - kexAlgoMap[kexAlgoECDH256] = &ecdh{elliptic.P256()} - kexAlgoMap[kexAlgoCurve25519SHA256] = &curve25519sha256{} -} - -// curve25519sha256 implements the curve25519-sha256@libssh.org key -// agreement protocol, as described in -// https://git.libssh.org/projects/libssh.git/tree/doc/curve25519-sha256@libssh.org.txt -type curve25519sha256 struct{} - -type curve25519KeyPair struct { - priv [32]byte - pub [32]byte -} - -func (kp *curve25519KeyPair) generate(rand io.Reader) error { - if _, err := io.ReadFull(rand, kp.priv[:]); err != nil { - return err - } - curve25519.ScalarBaseMult(&kp.pub, &kp.priv) - return nil -} - -// curve25519Zeros is just an array of 32 zero bytes so that we have something -// convenient to compare against in order to reject curve25519 points with the -// wrong order. -var curve25519Zeros [32]byte - -func (kex *curve25519sha256) Client(c packetConn, rand io.Reader, magics *handshakeMagics) (*kexResult, error) { - var kp curve25519KeyPair - if err := kp.generate(rand); err != nil { - return nil, err - } - if err := c.writePacket(Marshal(&kexECDHInitMsg{kp.pub[:]})); err != nil { - return nil, err - } - - packet, err := c.readPacket() - if err != nil { - return nil, err - } - - var reply kexECDHReplyMsg - if err = Unmarshal(packet, &reply); err != nil { - return nil, err - } - if len(reply.EphemeralPubKey) != 32 { - return nil, errors.New("ssh: peer's curve25519 public value has wrong length") - } - - var servPub, secret [32]byte - copy(servPub[:], reply.EphemeralPubKey) - curve25519.ScalarMult(&secret, &kp.priv, &servPub) - if subtle.ConstantTimeCompare(secret[:], curve25519Zeros[:]) == 1 { - return nil, errors.New("ssh: peer's curve25519 public value has wrong order") - } - - h := crypto.SHA256.New() - magics.write(h) - writeString(h, reply.HostKey) - writeString(h, kp.pub[:]) - writeString(h, reply.EphemeralPubKey) - - kInt := new(big.Int).SetBytes(secret[:]) - K := make([]byte, intLength(kInt)) - marshalInt(K, kInt) - h.Write(K) - - return &kexResult{ - H: h.Sum(nil), - K: K, - HostKey: reply.HostKey, - Signature: reply.Signature, - Hash: crypto.SHA256, - }, nil -} - -func (kex *curve25519sha256) Server(c packetConn, rand io.Reader, magics *handshakeMagics, priv Signer) (result *kexResult, err error) { - packet, err := c.readPacket() - if err != nil { - return - } - var kexInit kexECDHInitMsg - if err = Unmarshal(packet, &kexInit); err != nil { - return - } - - if len(kexInit.ClientPubKey) != 32 { - return nil, errors.New("ssh: peer's curve25519 public value has wrong length") - } - - var kp curve25519KeyPair - if err := kp.generate(rand); err != nil { - return nil, err - } - - var clientPub, secret [32]byte - copy(clientPub[:], kexInit.ClientPubKey) - curve25519.ScalarMult(&secret, &kp.priv, &clientPub) - if subtle.ConstantTimeCompare(secret[:], curve25519Zeros[:]) == 1 { - return nil, errors.New("ssh: peer's curve25519 public value has wrong order") - } - - hostKeyBytes := priv.PublicKey().Marshal() - - h := crypto.SHA256.New() - magics.write(h) - writeString(h, hostKeyBytes) - writeString(h, kexInit.ClientPubKey) - writeString(h, kp.pub[:]) - - kInt := new(big.Int).SetBytes(secret[:]) - K := make([]byte, intLength(kInt)) - marshalInt(K, kInt) - h.Write(K) - - H := h.Sum(nil) - - sig, err := signAndMarshal(priv, rand, H) - if err != nil { - return nil, err - } - - reply := kexECDHReplyMsg{ - EphemeralPubKey: kp.pub[:], - HostKey: hostKeyBytes, - Signature: sig, - } - if err := c.writePacket(Marshal(&reply)); err != nil { - return nil, err - } - return &kexResult{ - H: H, - K: K, - HostKey: hostKeyBytes, - Signature: sig, - Hash: crypto.SHA256, - }, nil -} diff --git a/vendor/golang.org/x/crypto/ssh/keys.go b/vendor/golang.org/x/crypto/ssh/keys.go deleted file mode 100644 index f2fc9b6..0000000 --- a/vendor/golang.org/x/crypto/ssh/keys.go +++ /dev/null @@ -1,880 +0,0 @@ -// Copyright 2012 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 ssh - -import ( - "bytes" - "crypto" - "crypto/dsa" - "crypto/ecdsa" - "crypto/elliptic" - "crypto/rsa" - "crypto/x509" - "encoding/asn1" - "encoding/base64" - "encoding/pem" - "errors" - "fmt" - "io" - "math/big" - "strings" - - "golang.org/x/crypto/ed25519" -) - -// These constants represent the algorithm names for key types supported by this -// package. -const ( - KeyAlgoRSA = "ssh-rsa" - KeyAlgoDSA = "ssh-dss" - KeyAlgoECDSA256 = "ecdsa-sha2-nistp256" - KeyAlgoECDSA384 = "ecdsa-sha2-nistp384" - KeyAlgoECDSA521 = "ecdsa-sha2-nistp521" - KeyAlgoED25519 = "ssh-ed25519" -) - -// parsePubKey parses a public key of the given algorithm. -// Use ParsePublicKey for keys with prepended algorithm. -func parsePubKey(in []byte, algo string) (pubKey PublicKey, rest []byte, err error) { - switch algo { - case KeyAlgoRSA: - return parseRSA(in) - case KeyAlgoDSA: - return parseDSA(in) - case KeyAlgoECDSA256, KeyAlgoECDSA384, KeyAlgoECDSA521: - return parseECDSA(in) - case KeyAlgoED25519: - return parseED25519(in) - case CertAlgoRSAv01, CertAlgoDSAv01, CertAlgoECDSA256v01, CertAlgoECDSA384v01, CertAlgoECDSA521v01, CertAlgoED25519v01: - cert, err := parseCert(in, certToPrivAlgo(algo)) - if err != nil { - return nil, nil, err - } - return cert, nil, nil - } - return nil, nil, fmt.Errorf("ssh: unknown key algorithm: %v", algo) -} - -// parseAuthorizedKey parses a public key in OpenSSH authorized_keys format -// (see sshd(8) manual page) once the options and key type fields have been -// removed. -func parseAuthorizedKey(in []byte) (out PublicKey, comment string, err error) { - in = bytes.TrimSpace(in) - - i := bytes.IndexAny(in, " \t") - if i == -1 { - i = len(in) - } - base64Key := in[:i] - - key := make([]byte, base64.StdEncoding.DecodedLen(len(base64Key))) - n, err := base64.StdEncoding.Decode(key, base64Key) - if err != nil { - return nil, "", err - } - key = key[:n] - out, err = ParsePublicKey(key) - if err != nil { - return nil, "", err - } - comment = string(bytes.TrimSpace(in[i:])) - return out, comment, nil -} - -// ParseKnownHosts parses an entry in the format of the known_hosts file. -// -// The known_hosts format is documented in the sshd(8) manual page. This -// function will parse a single entry from in. On successful return, marker -// will contain the optional marker value (i.e. "cert-authority" or "revoked") -// or else be empty, hosts will contain the hosts that this entry matches, -// pubKey will contain the public key and comment will contain any trailing -// comment at the end of the line. See the sshd(8) manual page for the various -// forms that a host string can take. -// -// The unparsed remainder of the input will be returned in rest. This function -// can be called repeatedly to parse multiple entries. -// -// If no entries were found in the input then err will be io.EOF. Otherwise a -// non-nil err value indicates a parse error. -func ParseKnownHosts(in []byte) (marker string, hosts []string, pubKey PublicKey, comment string, rest []byte, err error) { - for len(in) > 0 { - end := bytes.IndexByte(in, '\n') - if end != -1 { - rest = in[end+1:] - in = in[:end] - } else { - rest = nil - } - - end = bytes.IndexByte(in, '\r') - if end != -1 { - in = in[:end] - } - - in = bytes.TrimSpace(in) - if len(in) == 0 || in[0] == '#' { - in = rest - continue - } - - i := bytes.IndexAny(in, " \t") - if i == -1 { - in = rest - continue - } - - // Strip out the beginning of the known_host key. - // This is either an optional marker or a (set of) hostname(s). - keyFields := bytes.Fields(in) - if len(keyFields) < 3 || len(keyFields) > 5 { - return "", nil, nil, "", nil, errors.New("ssh: invalid entry in known_hosts data") - } - - // keyFields[0] is either "@cert-authority", "@revoked" or a comma separated - // list of hosts - marker := "" - if keyFields[0][0] == '@' { - marker = string(keyFields[0][1:]) - keyFields = keyFields[1:] - } - - hosts := string(keyFields[0]) - // keyFields[1] contains the key type (e.g. “ssh-rsa”). - // However, that information is duplicated inside the - // base64-encoded key and so is ignored here. - - key := bytes.Join(keyFields[2:], []byte(" ")) - if pubKey, comment, err = parseAuthorizedKey(key); err != nil { - return "", nil, nil, "", nil, err - } - - return marker, strings.Split(hosts, ","), pubKey, comment, rest, nil - } - - return "", nil, nil, "", nil, io.EOF -} - -// ParseAuthorizedKeys parses a public key from an authorized_keys -// file used in OpenSSH according to the sshd(8) manual page. -func ParseAuthorizedKey(in []byte) (out PublicKey, comment string, options []string, rest []byte, err error) { - for len(in) > 0 { - end := bytes.IndexByte(in, '\n') - if end != -1 { - rest = in[end+1:] - in = in[:end] - } else { - rest = nil - } - - end = bytes.IndexByte(in, '\r') - if end != -1 { - in = in[:end] - } - - in = bytes.TrimSpace(in) - if len(in) == 0 || in[0] == '#' { - in = rest - continue - } - - i := bytes.IndexAny(in, " \t") - if i == -1 { - in = rest - continue - } - - if out, comment, err = parseAuthorizedKey(in[i:]); err == nil { - return out, comment, options, rest, nil - } - - // No key type recognised. Maybe there's an options field at - // the beginning. - var b byte - inQuote := false - var candidateOptions []string - optionStart := 0 - for i, b = range in { - isEnd := !inQuote && (b == ' ' || b == '\t') - if (b == ',' && !inQuote) || isEnd { - if i-optionStart > 0 { - candidateOptions = append(candidateOptions, string(in[optionStart:i])) - } - optionStart = i + 1 - } - if isEnd { - break - } - if b == '"' && (i == 0 || (i > 0 && in[i-1] != '\\')) { - inQuote = !inQuote - } - } - for i < len(in) && (in[i] == ' ' || in[i] == '\t') { - i++ - } - if i == len(in) { - // Invalid line: unmatched quote - in = rest - continue - } - - in = in[i:] - i = bytes.IndexAny(in, " \t") - if i == -1 { - in = rest - continue - } - - if out, comment, err = parseAuthorizedKey(in[i:]); err == nil { - options = candidateOptions - return out, comment, options, rest, nil - } - - in = rest - continue - } - - return nil, "", nil, nil, errors.New("ssh: no key found") -} - -// ParsePublicKey parses an SSH public key formatted for use in -// the SSH wire protocol according to RFC 4253, section 6.6. -func ParsePublicKey(in []byte) (out PublicKey, err error) { - algo, in, ok := parseString(in) - if !ok { - return nil, errShortRead - } - var rest []byte - out, rest, err = parsePubKey(in, string(algo)) - if len(rest) > 0 { - return nil, errors.New("ssh: trailing junk in public key") - } - - return out, err -} - -// MarshalAuthorizedKey serializes key for inclusion in an OpenSSH -// authorized_keys file. The return value ends with newline. -func MarshalAuthorizedKey(key PublicKey) []byte { - b := &bytes.Buffer{} - b.WriteString(key.Type()) - b.WriteByte(' ') - e := base64.NewEncoder(base64.StdEncoding, b) - e.Write(key.Marshal()) - e.Close() - b.WriteByte('\n') - return b.Bytes() -} - -// PublicKey is an abstraction of different types of public keys. -type PublicKey interface { - // Type returns the key's type, e.g. "ssh-rsa". - Type() string - - // Marshal returns the serialized key data in SSH wire format, - // with the name prefix. - Marshal() []byte - - // Verify that sig is a signature on the given data using this - // key. This function will hash the data appropriately first. - Verify(data []byte, sig *Signature) error -} - -// CryptoPublicKey, if implemented by a PublicKey, -// returns the underlying crypto.PublicKey form of the key. -type CryptoPublicKey interface { - CryptoPublicKey() crypto.PublicKey -} - -// A Signer can create signatures that verify against a public key. -type Signer interface { - // PublicKey returns an associated PublicKey instance. - PublicKey() PublicKey - - // Sign returns raw signature for the given data. This method - // will apply the hash specified for the keytype to the data. - Sign(rand io.Reader, data []byte) (*Signature, error) -} - -type rsaPublicKey rsa.PublicKey - -func (r *rsaPublicKey) Type() string { - return "ssh-rsa" -} - -// parseRSA parses an RSA key according to RFC 4253, section 6.6. -func parseRSA(in []byte) (out PublicKey, rest []byte, err error) { - var w struct { - E *big.Int - N *big.Int - Rest []byte `ssh:"rest"` - } - if err := Unmarshal(in, &w); err != nil { - return nil, nil, err - } - - if w.E.BitLen() > 24 { - return nil, nil, errors.New("ssh: exponent too large") - } - e := w.E.Int64() - if e < 3 || e&1 == 0 { - return nil, nil, errors.New("ssh: incorrect exponent") - } - - var key rsa.PublicKey - key.E = int(e) - key.N = w.N - return (*rsaPublicKey)(&key), w.Rest, nil -} - -func (r *rsaPublicKey) Marshal() []byte { - e := new(big.Int).SetInt64(int64(r.E)) - // RSA publickey struct layout should match the struct used by - // parseRSACert in the x/crypto/ssh/agent package. - wirekey := struct { - Name string - E *big.Int - N *big.Int - }{ - KeyAlgoRSA, - e, - r.N, - } - return Marshal(&wirekey) -} - -func (r *rsaPublicKey) Verify(data []byte, sig *Signature) error { - if sig.Format != r.Type() { - return fmt.Errorf("ssh: signature type %s for key type %s", sig.Format, r.Type()) - } - h := crypto.SHA1.New() - h.Write(data) - digest := h.Sum(nil) - return rsa.VerifyPKCS1v15((*rsa.PublicKey)(r), crypto.SHA1, digest, sig.Blob) -} - -func (r *rsaPublicKey) CryptoPublicKey() crypto.PublicKey { - return (*rsa.PublicKey)(r) -} - -type dsaPublicKey dsa.PublicKey - -func (r *dsaPublicKey) Type() string { - return "ssh-dss" -} - -// parseDSA parses an DSA key according to RFC 4253, section 6.6. -func parseDSA(in []byte) (out PublicKey, rest []byte, err error) { - var w struct { - P, Q, G, Y *big.Int - Rest []byte `ssh:"rest"` - } - if err := Unmarshal(in, &w); err != nil { - return nil, nil, err - } - - key := &dsaPublicKey{ - Parameters: dsa.Parameters{ - P: w.P, - Q: w.Q, - G: w.G, - }, - Y: w.Y, - } - return key, w.Rest, nil -} - -func (k *dsaPublicKey) Marshal() []byte { - // DSA publickey struct layout should match the struct used by - // parseDSACert in the x/crypto/ssh/agent package. - w := struct { - Name string - P, Q, G, Y *big.Int - }{ - k.Type(), - k.P, - k.Q, - k.G, - k.Y, - } - - return Marshal(&w) -} - -func (k *dsaPublicKey) Verify(data []byte, sig *Signature) error { - if sig.Format != k.Type() { - return fmt.Errorf("ssh: signature type %s for key type %s", sig.Format, k.Type()) - } - h := crypto.SHA1.New() - h.Write(data) - digest := h.Sum(nil) - - // Per RFC 4253, section 6.6, - // The value for 'dss_signature_blob' is encoded as a string containing - // r, followed by s (which are 160-bit integers, without lengths or - // padding, unsigned, and in network byte order). - // For DSS purposes, sig.Blob should be exactly 40 bytes in length. - if len(sig.Blob) != 40 { - return errors.New("ssh: DSA signature parse error") - } - r := new(big.Int).SetBytes(sig.Blob[:20]) - s := new(big.Int).SetBytes(sig.Blob[20:]) - if dsa.Verify((*dsa.PublicKey)(k), digest, r, s) { - return nil - } - return errors.New("ssh: signature did not verify") -} - -func (k *dsaPublicKey) CryptoPublicKey() crypto.PublicKey { - return (*dsa.PublicKey)(k) -} - -type dsaPrivateKey struct { - *dsa.PrivateKey -} - -func (k *dsaPrivateKey) PublicKey() PublicKey { - return (*dsaPublicKey)(&k.PrivateKey.PublicKey) -} - -func (k *dsaPrivateKey) Sign(rand io.Reader, data []byte) (*Signature, error) { - h := crypto.SHA1.New() - h.Write(data) - digest := h.Sum(nil) - r, s, err := dsa.Sign(rand, k.PrivateKey, digest) - if err != nil { - return nil, err - } - - sig := make([]byte, 40) - rb := r.Bytes() - sb := s.Bytes() - - copy(sig[20-len(rb):20], rb) - copy(sig[40-len(sb):], sb) - - return &Signature{ - Format: k.PublicKey().Type(), - Blob: sig, - }, nil -} - -type ecdsaPublicKey ecdsa.PublicKey - -func (key *ecdsaPublicKey) Type() string { - return "ecdsa-sha2-" + key.nistID() -} - -func (key *ecdsaPublicKey) nistID() string { - switch key.Params().BitSize { - case 256: - return "nistp256" - case 384: - return "nistp384" - case 521: - return "nistp521" - } - panic("ssh: unsupported ecdsa key size") -} - -type ed25519PublicKey ed25519.PublicKey - -func (key ed25519PublicKey) Type() string { - return KeyAlgoED25519 -} - -func parseED25519(in []byte) (out PublicKey, rest []byte, err error) { - var w struct { - KeyBytes []byte - Rest []byte `ssh:"rest"` - } - - if err := Unmarshal(in, &w); err != nil { - return nil, nil, err - } - - key := ed25519.PublicKey(w.KeyBytes) - - return (ed25519PublicKey)(key), w.Rest, nil -} - -func (key ed25519PublicKey) Marshal() []byte { - w := struct { - Name string - KeyBytes []byte - }{ - KeyAlgoED25519, - []byte(key), - } - return Marshal(&w) -} - -func (key ed25519PublicKey) Verify(b []byte, sig *Signature) error { - if sig.Format != key.Type() { - return fmt.Errorf("ssh: signature type %s for key type %s", sig.Format, key.Type()) - } - - edKey := (ed25519.PublicKey)(key) - if ok := ed25519.Verify(edKey, b, sig.Blob); !ok { - return errors.New("ssh: signature did not verify") - } - - return nil -} - -func (k ed25519PublicKey) CryptoPublicKey() crypto.PublicKey { - return ed25519.PublicKey(k) -} - -func supportedEllipticCurve(curve elliptic.Curve) bool { - return curve == elliptic.P256() || curve == elliptic.P384() || curve == elliptic.P521() -} - -// ecHash returns the hash to match the given elliptic curve, see RFC -// 5656, section 6.2.1 -func ecHash(curve elliptic.Curve) crypto.Hash { - bitSize := curve.Params().BitSize - switch { - case bitSize <= 256: - return crypto.SHA256 - case bitSize <= 384: - return crypto.SHA384 - } - return crypto.SHA512 -} - -// parseECDSA parses an ECDSA key according to RFC 5656, section 3.1. -func parseECDSA(in []byte) (out PublicKey, rest []byte, err error) { - var w struct { - Curve string - KeyBytes []byte - Rest []byte `ssh:"rest"` - } - - if err := Unmarshal(in, &w); err != nil { - return nil, nil, err - } - - key := new(ecdsa.PublicKey) - - switch w.Curve { - case "nistp256": - key.Curve = elliptic.P256() - case "nistp384": - key.Curve = elliptic.P384() - case "nistp521": - key.Curve = elliptic.P521() - default: - return nil, nil, errors.New("ssh: unsupported curve") - } - - key.X, key.Y = elliptic.Unmarshal(key.Curve, w.KeyBytes) - if key.X == nil || key.Y == nil { - return nil, nil, errors.New("ssh: invalid curve point") - } - return (*ecdsaPublicKey)(key), w.Rest, nil -} - -func (key *ecdsaPublicKey) Marshal() []byte { - // See RFC 5656, section 3.1. - keyBytes := elliptic.Marshal(key.Curve, key.X, key.Y) - // ECDSA publickey struct layout should match the struct used by - // parseECDSACert in the x/crypto/ssh/agent package. - w := struct { - Name string - ID string - Key []byte - }{ - key.Type(), - key.nistID(), - keyBytes, - } - - return Marshal(&w) -} - -func (key *ecdsaPublicKey) Verify(data []byte, sig *Signature) error { - if sig.Format != key.Type() { - return fmt.Errorf("ssh: signature type %s for key type %s", sig.Format, key.Type()) - } - - h := ecHash(key.Curve).New() - h.Write(data) - digest := h.Sum(nil) - - // Per RFC 5656, section 3.1.2, - // The ecdsa_signature_blob value has the following specific encoding: - // mpint r - // mpint s - var ecSig struct { - R *big.Int - S *big.Int - } - - if err := Unmarshal(sig.Blob, &ecSig); err != nil { - return err - } - - if ecdsa.Verify((*ecdsa.PublicKey)(key), digest, ecSig.R, ecSig.S) { - return nil - } - return errors.New("ssh: signature did not verify") -} - -func (k *ecdsaPublicKey) CryptoPublicKey() crypto.PublicKey { - return (*ecdsa.PublicKey)(k) -} - -// NewSignerFromKey takes an *rsa.PrivateKey, *dsa.PrivateKey, -// *ecdsa.PrivateKey or any other crypto.Signer and returns a corresponding -// Signer instance. ECDSA keys must use P-256, P-384 or P-521. -func NewSignerFromKey(key interface{}) (Signer, error) { - switch key := key.(type) { - case crypto.Signer: - return NewSignerFromSigner(key) - case *dsa.PrivateKey: - return &dsaPrivateKey{key}, nil - default: - return nil, fmt.Errorf("ssh: unsupported key type %T", key) - } -} - -type wrappedSigner struct { - signer crypto.Signer - pubKey PublicKey -} - -// NewSignerFromSigner takes any crypto.Signer implementation and -// returns a corresponding Signer interface. This can be used, for -// example, with keys kept in hardware modules. -func NewSignerFromSigner(signer crypto.Signer) (Signer, error) { - pubKey, err := NewPublicKey(signer.Public()) - if err != nil { - return nil, err - } - - return &wrappedSigner{signer, pubKey}, nil -} - -func (s *wrappedSigner) PublicKey() PublicKey { - return s.pubKey -} - -func (s *wrappedSigner) Sign(rand io.Reader, data []byte) (*Signature, error) { - var hashFunc crypto.Hash - - switch key := s.pubKey.(type) { - case *rsaPublicKey, *dsaPublicKey: - hashFunc = crypto.SHA1 - case *ecdsaPublicKey: - hashFunc = ecHash(key.Curve) - case ed25519PublicKey: - default: - return nil, fmt.Errorf("ssh: unsupported key type %T", key) - } - - var digest []byte - if hashFunc != 0 { - h := hashFunc.New() - h.Write(data) - digest = h.Sum(nil) - } else { - digest = data - } - - signature, err := s.signer.Sign(rand, digest, hashFunc) - if err != nil { - return nil, err - } - - // crypto.Signer.Sign is expected to return an ASN.1-encoded signature - // for ECDSA and DSA, but that's not the encoding expected by SSH, so - // re-encode. - switch s.pubKey.(type) { - case *ecdsaPublicKey, *dsaPublicKey: - type asn1Signature struct { - R, S *big.Int - } - asn1Sig := new(asn1Signature) - _, err := asn1.Unmarshal(signature, asn1Sig) - if err != nil { - return nil, err - } - - switch s.pubKey.(type) { - case *ecdsaPublicKey: - signature = Marshal(asn1Sig) - - case *dsaPublicKey: - signature = make([]byte, 40) - r := asn1Sig.R.Bytes() - s := asn1Sig.S.Bytes() - copy(signature[20-len(r):20], r) - copy(signature[40-len(s):40], s) - } - } - - return &Signature{ - Format: s.pubKey.Type(), - Blob: signature, - }, nil -} - -// NewPublicKey takes an *rsa.PublicKey, *dsa.PublicKey, *ecdsa.PublicKey, -// or ed25519.PublicKey returns a corresponding PublicKey instance. -// ECDSA keys must use P-256, P-384 or P-521. -func NewPublicKey(key interface{}) (PublicKey, error) { - switch key := key.(type) { - case *rsa.PublicKey: - return (*rsaPublicKey)(key), nil - case *ecdsa.PublicKey: - if !supportedEllipticCurve(key.Curve) { - return nil, errors.New("ssh: only P-256, P-384 and P-521 EC keys are supported.") - } - return (*ecdsaPublicKey)(key), nil - case *dsa.PublicKey: - return (*dsaPublicKey)(key), nil - case ed25519.PublicKey: - return (ed25519PublicKey)(key), nil - default: - return nil, fmt.Errorf("ssh: unsupported key type %T", key) - } -} - -// ParsePrivateKey returns a Signer from a PEM encoded private key. It supports -// the same keys as ParseRawPrivateKey. -func ParsePrivateKey(pemBytes []byte) (Signer, error) { - key, err := ParseRawPrivateKey(pemBytes) - if err != nil { - return nil, err - } - - return NewSignerFromKey(key) -} - -// encryptedBlock tells whether a private key is -// encrypted by examining its Proc-Type header -// for a mention of ENCRYPTED -// according to RFC 1421 Section 4.6.1.1. -func encryptedBlock(block *pem.Block) bool { - return strings.Contains(block.Headers["Proc-Type"], "ENCRYPTED") -} - -// ParseRawPrivateKey returns a private key from a PEM encoded private key. It -// supports RSA (PKCS#1), DSA (OpenSSL), and ECDSA private keys. -func ParseRawPrivateKey(pemBytes []byte) (interface{}, error) { - block, _ := pem.Decode(pemBytes) - if block == nil { - return nil, errors.New("ssh: no key found") - } - - if encryptedBlock(block) { - return nil, errors.New("ssh: cannot decode encrypted private keys") - } - - switch block.Type { - case "RSA PRIVATE KEY": - return x509.ParsePKCS1PrivateKey(block.Bytes) - case "EC PRIVATE KEY": - return x509.ParseECPrivateKey(block.Bytes) - case "DSA PRIVATE KEY": - return ParseDSAPrivateKey(block.Bytes) - case "OPENSSH PRIVATE KEY": - return parseOpenSSHPrivateKey(block.Bytes) - default: - return nil, fmt.Errorf("ssh: unsupported key type %q", block.Type) - } -} - -// ParseDSAPrivateKey returns a DSA private key from its ASN.1 DER encoding, as -// specified by the OpenSSL DSA man page. -func ParseDSAPrivateKey(der []byte) (*dsa.PrivateKey, error) { - var k struct { - Version int - P *big.Int - Q *big.Int - G *big.Int - Priv *big.Int - Pub *big.Int - } - rest, err := asn1.Unmarshal(der, &k) - if err != nil { - return nil, errors.New("ssh: failed to parse DSA key: " + err.Error()) - } - if len(rest) > 0 { - return nil, errors.New("ssh: garbage after DSA key") - } - - return &dsa.PrivateKey{ - PublicKey: dsa.PublicKey{ - Parameters: dsa.Parameters{ - P: k.P, - Q: k.Q, - G: k.G, - }, - Y: k.Priv, - }, - X: k.Pub, - }, nil -} - -// Implemented based on the documentation at -// https://github.com/openssh/openssh-portable/blob/master/PROTOCOL.key -func parseOpenSSHPrivateKey(key []byte) (*ed25519.PrivateKey, error) { - magic := append([]byte("openssh-key-v1"), 0) - if !bytes.Equal(magic, key[0:len(magic)]) { - return nil, errors.New("ssh: invalid openssh private key format") - } - remaining := key[len(magic):] - - var w struct { - CipherName string - KdfName string - KdfOpts string - NumKeys uint32 - PubKey []byte - PrivKeyBlock []byte - } - - if err := Unmarshal(remaining, &w); err != nil { - return nil, err - } - - pk1 := struct { - Check1 uint32 - Check2 uint32 - Keytype string - Pub []byte - Priv []byte - Comment string - Pad []byte `ssh:"rest"` - }{} - - if err := Unmarshal(w.PrivKeyBlock, &pk1); err != nil { - return nil, err - } - - if pk1.Check1 != pk1.Check2 { - return nil, errors.New("ssh: checkint mismatch") - } - - // we only handle ed25519 keys currently - if pk1.Keytype != KeyAlgoED25519 { - return nil, errors.New("ssh: unhandled key type") - } - - for i, b := range pk1.Pad { - if int(b) != i+1 { - return nil, errors.New("ssh: padding not as expected") - } - } - - if len(pk1.Priv) != ed25519.PrivateKeySize { - return nil, errors.New("ssh: private key unexpected length") - } - - pk := ed25519.PrivateKey(make([]byte, ed25519.PrivateKeySize)) - copy(pk, pk1.Priv) - return &pk, nil -} diff --git a/vendor/golang.org/x/crypto/ssh/mac.go b/vendor/golang.org/x/crypto/ssh/mac.go deleted file mode 100644 index 07744ad..0000000 --- a/vendor/golang.org/x/crypto/ssh/mac.go +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright 2012 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 ssh - -// Message authentication support - -import ( - "crypto/hmac" - "crypto/sha1" - "crypto/sha256" - "hash" -) - -type macMode struct { - keySize int - new func(key []byte) hash.Hash -} - -// truncatingMAC wraps around a hash.Hash and truncates the output digest to -// a given size. -type truncatingMAC struct { - length int - hmac hash.Hash -} - -func (t truncatingMAC) Write(data []byte) (int, error) { - return t.hmac.Write(data) -} - -func (t truncatingMAC) Sum(in []byte) []byte { - out := t.hmac.Sum(in) - return out[:len(in)+t.length] -} - -func (t truncatingMAC) Reset() { - t.hmac.Reset() -} - -func (t truncatingMAC) Size() int { - return t.length -} - -func (t truncatingMAC) BlockSize() int { return t.hmac.BlockSize() } - -var macModes = map[string]*macMode{ - "hmac-sha2-256": {32, func(key []byte) hash.Hash { - return hmac.New(sha256.New, key) - }}, - "hmac-sha1": {20, func(key []byte) hash.Hash { - return hmac.New(sha1.New, key) - }}, - "hmac-sha1-96": {20, func(key []byte) hash.Hash { - return truncatingMAC{12, hmac.New(sha1.New, key)} - }}, -} diff --git a/vendor/golang.org/x/crypto/ssh/messages.go b/vendor/golang.org/x/crypto/ssh/messages.go deleted file mode 100644 index e6ecd3a..0000000 --- a/vendor/golang.org/x/crypto/ssh/messages.go +++ /dev/null @@ -1,758 +0,0 @@ -// Copyright 2011 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 ssh - -import ( - "bytes" - "encoding/binary" - "errors" - "fmt" - "io" - "math/big" - "reflect" - "strconv" - "strings" -) - -// These are SSH message type numbers. They are scattered around several -// documents but many were taken from [SSH-PARAMETERS]. -const ( - msgIgnore = 2 - msgUnimplemented = 3 - msgDebug = 4 - msgNewKeys = 21 - - // Standard authentication messages - msgUserAuthSuccess = 52 - msgUserAuthBanner = 53 -) - -// SSH messages: -// -// These structures mirror the wire format of the corresponding SSH messages. -// They are marshaled using reflection with the marshal and unmarshal functions -// in this file. The only wrinkle is that a final member of type []byte with a -// ssh tag of "rest" receives the remainder of a packet when unmarshaling. - -// See RFC 4253, section 11.1. -const msgDisconnect = 1 - -// disconnectMsg is the message that signals a disconnect. It is also -// the error type returned from mux.Wait() -type disconnectMsg struct { - Reason uint32 `sshtype:"1"` - Message string - Language string -} - -func (d *disconnectMsg) Error() string { - return fmt.Sprintf("ssh: disconnect, reason %d: %s", d.Reason, d.Message) -} - -// See RFC 4253, section 7.1. -const msgKexInit = 20 - -type kexInitMsg struct { - Cookie [16]byte `sshtype:"20"` - KexAlgos []string - ServerHostKeyAlgos []string - CiphersClientServer []string - CiphersServerClient []string - MACsClientServer []string - MACsServerClient []string - CompressionClientServer []string - CompressionServerClient []string - LanguagesClientServer []string - LanguagesServerClient []string - FirstKexFollows bool - Reserved uint32 -} - -// See RFC 4253, section 8. - -// Diffie-Helman -const msgKexDHInit = 30 - -type kexDHInitMsg struct { - X *big.Int `sshtype:"30"` -} - -const msgKexECDHInit = 30 - -type kexECDHInitMsg struct { - ClientPubKey []byte `sshtype:"30"` -} - -const msgKexECDHReply = 31 - -type kexECDHReplyMsg struct { - HostKey []byte `sshtype:"31"` - EphemeralPubKey []byte - Signature []byte -} - -const msgKexDHReply = 31 - -type kexDHReplyMsg struct { - HostKey []byte `sshtype:"31"` - Y *big.Int - Signature []byte -} - -// See RFC 4253, section 10. -const msgServiceRequest = 5 - -type serviceRequestMsg struct { - Service string `sshtype:"5"` -} - -// See RFC 4253, section 10. -const msgServiceAccept = 6 - -type serviceAcceptMsg struct { - Service string `sshtype:"6"` -} - -// See RFC 4252, section 5. -const msgUserAuthRequest = 50 - -type userAuthRequestMsg struct { - User string `sshtype:"50"` - Service string - Method string - Payload []byte `ssh:"rest"` -} - -// Used for debug printouts of packets. -type userAuthSuccessMsg struct { -} - -// See RFC 4252, section 5.1 -const msgUserAuthFailure = 51 - -type userAuthFailureMsg struct { - Methods []string `sshtype:"51"` - PartialSuccess bool -} - -// See RFC 4256, section 3.2 -const msgUserAuthInfoRequest = 60 -const msgUserAuthInfoResponse = 61 - -type userAuthInfoRequestMsg struct { - User string `sshtype:"60"` - Instruction string - DeprecatedLanguage string - NumPrompts uint32 - Prompts []byte `ssh:"rest"` -} - -// See RFC 4254, section 5.1. -const msgChannelOpen = 90 - -type channelOpenMsg struct { - ChanType string `sshtype:"90"` - PeersId uint32 - PeersWindow uint32 - MaxPacketSize uint32 - TypeSpecificData []byte `ssh:"rest"` -} - -const msgChannelExtendedData = 95 -const msgChannelData = 94 - -// Used for debug print outs of packets. -type channelDataMsg struct { - PeersId uint32 `sshtype:"94"` - Length uint32 - Rest []byte `ssh:"rest"` -} - -// See RFC 4254, section 5.1. -const msgChannelOpenConfirm = 91 - -type channelOpenConfirmMsg struct { - PeersId uint32 `sshtype:"91"` - MyId uint32 - MyWindow uint32 - MaxPacketSize uint32 - TypeSpecificData []byte `ssh:"rest"` -} - -// See RFC 4254, section 5.1. -const msgChannelOpenFailure = 92 - -type channelOpenFailureMsg struct { - PeersId uint32 `sshtype:"92"` - Reason RejectionReason - Message string - Language string -} - -const msgChannelRequest = 98 - -type channelRequestMsg struct { - PeersId uint32 `sshtype:"98"` - Request string - WantReply bool - RequestSpecificData []byte `ssh:"rest"` -} - -// See RFC 4254, section 5.4. -const msgChannelSuccess = 99 - -type channelRequestSuccessMsg struct { - PeersId uint32 `sshtype:"99"` -} - -// See RFC 4254, section 5.4. -const msgChannelFailure = 100 - -type channelRequestFailureMsg struct { - PeersId uint32 `sshtype:"100"` -} - -// See RFC 4254, section 5.3 -const msgChannelClose = 97 - -type channelCloseMsg struct { - PeersId uint32 `sshtype:"97"` -} - -// See RFC 4254, section 5.3 -const msgChannelEOF = 96 - -type channelEOFMsg struct { - PeersId uint32 `sshtype:"96"` -} - -// See RFC 4254, section 4 -const msgGlobalRequest = 80 - -type globalRequestMsg struct { - Type string `sshtype:"80"` - WantReply bool - Data []byte `ssh:"rest"` -} - -// See RFC 4254, section 4 -const msgRequestSuccess = 81 - -type globalRequestSuccessMsg struct { - Data []byte `ssh:"rest" sshtype:"81"` -} - -// See RFC 4254, section 4 -const msgRequestFailure = 82 - -type globalRequestFailureMsg struct { - Data []byte `ssh:"rest" sshtype:"82"` -} - -// See RFC 4254, section 5.2 -const msgChannelWindowAdjust = 93 - -type windowAdjustMsg struct { - PeersId uint32 `sshtype:"93"` - AdditionalBytes uint32 -} - -// See RFC 4252, section 7 -const msgUserAuthPubKeyOk = 60 - -type userAuthPubKeyOkMsg struct { - Algo string `sshtype:"60"` - PubKey []byte -} - -// typeTags returns the possible type bytes for the given reflect.Type, which -// should be a struct. The possible values are separated by a '|' character. -func typeTags(structType reflect.Type) (tags []byte) { - tagStr := structType.Field(0).Tag.Get("sshtype") - - for _, tag := range strings.Split(tagStr, "|") { - i, err := strconv.Atoi(tag) - if err == nil { - tags = append(tags, byte(i)) - } - } - - return tags -} - -func fieldError(t reflect.Type, field int, problem string) error { - if problem != "" { - problem = ": " + problem - } - return fmt.Errorf("ssh: unmarshal error for field %s of type %s%s", t.Field(field).Name, t.Name(), problem) -} - -var errShortRead = errors.New("ssh: short read") - -// Unmarshal parses data in SSH wire format into a structure. The out -// argument should be a pointer to struct. If the first member of the -// struct has the "sshtype" tag set to a '|'-separated set of numbers -// in decimal, the packet must start with one of those numbers. In -// case of error, Unmarshal returns a ParseError or -// UnexpectedMessageError. -func Unmarshal(data []byte, out interface{}) error { - v := reflect.ValueOf(out).Elem() - structType := v.Type() - expectedTypes := typeTags(structType) - - var expectedType byte - if len(expectedTypes) > 0 { - expectedType = expectedTypes[0] - } - - if len(data) == 0 { - return parseError(expectedType) - } - - if len(expectedTypes) > 0 { - goodType := false - for _, e := range expectedTypes { - if e > 0 && data[0] == e { - goodType = true - break - } - } - if !goodType { - return fmt.Errorf("ssh: unexpected message type %d (expected one of %v)", data[0], expectedTypes) - } - data = data[1:] - } - - var ok bool - for i := 0; i < v.NumField(); i++ { - field := v.Field(i) - t := field.Type() - switch t.Kind() { - case reflect.Bool: - if len(data) < 1 { - return errShortRead - } - field.SetBool(data[0] != 0) - data = data[1:] - case reflect.Array: - if t.Elem().Kind() != reflect.Uint8 { - return fieldError(structType, i, "array of unsupported type") - } - if len(data) < t.Len() { - return errShortRead - } - for j, n := 0, t.Len(); j < n; j++ { - field.Index(j).Set(reflect.ValueOf(data[j])) - } - data = data[t.Len():] - case reflect.Uint64: - var u64 uint64 - if u64, data, ok = parseUint64(data); !ok { - return errShortRead - } - field.SetUint(u64) - case reflect.Uint32: - var u32 uint32 - if u32, data, ok = parseUint32(data); !ok { - return errShortRead - } - field.SetUint(uint64(u32)) - case reflect.Uint8: - if len(data) < 1 { - return errShortRead - } - field.SetUint(uint64(data[0])) - data = data[1:] - case reflect.String: - var s []byte - if s, data, ok = parseString(data); !ok { - return fieldError(structType, i, "") - } - field.SetString(string(s)) - case reflect.Slice: - switch t.Elem().Kind() { - case reflect.Uint8: - if structType.Field(i).Tag.Get("ssh") == "rest" { - field.Set(reflect.ValueOf(data)) - data = nil - } else { - var s []byte - if s, data, ok = parseString(data); !ok { - return errShortRead - } - field.Set(reflect.ValueOf(s)) - } - case reflect.String: - var nl []string - if nl, data, ok = parseNameList(data); !ok { - return errShortRead - } - field.Set(reflect.ValueOf(nl)) - default: - return fieldError(structType, i, "slice of unsupported type") - } - case reflect.Ptr: - if t == bigIntType { - var n *big.Int - if n, data, ok = parseInt(data); !ok { - return errShortRead - } - field.Set(reflect.ValueOf(n)) - } else { - return fieldError(structType, i, "pointer to unsupported type") - } - default: - return fieldError(structType, i, fmt.Sprintf("unsupported type: %v", t)) - } - } - - if len(data) != 0 { - return parseError(expectedType) - } - - return nil -} - -// Marshal serializes the message in msg to SSH wire format. The msg -// argument should be a struct or pointer to struct. If the first -// member has the "sshtype" tag set to a number in decimal, that -// number is prepended to the result. If the last of member has the -// "ssh" tag set to "rest", its contents are appended to the output. -func Marshal(msg interface{}) []byte { - out := make([]byte, 0, 64) - return marshalStruct(out, msg) -} - -func marshalStruct(out []byte, msg interface{}) []byte { - v := reflect.Indirect(reflect.ValueOf(msg)) - msgTypes := typeTags(v.Type()) - if len(msgTypes) > 0 { - out = append(out, msgTypes[0]) - } - - for i, n := 0, v.NumField(); i < n; i++ { - field := v.Field(i) - switch t := field.Type(); t.Kind() { - case reflect.Bool: - var v uint8 - if field.Bool() { - v = 1 - } - out = append(out, v) - case reflect.Array: - if t.Elem().Kind() != reflect.Uint8 { - panic(fmt.Sprintf("array of non-uint8 in field %d: %T", i, field.Interface())) - } - for j, l := 0, t.Len(); j < l; j++ { - out = append(out, uint8(field.Index(j).Uint())) - } - case reflect.Uint32: - out = appendU32(out, uint32(field.Uint())) - case reflect.Uint64: - out = appendU64(out, uint64(field.Uint())) - case reflect.Uint8: - out = append(out, uint8(field.Uint())) - case reflect.String: - s := field.String() - out = appendInt(out, len(s)) - out = append(out, s...) - case reflect.Slice: - switch t.Elem().Kind() { - case reflect.Uint8: - if v.Type().Field(i).Tag.Get("ssh") != "rest" { - out = appendInt(out, field.Len()) - } - out = append(out, field.Bytes()...) - case reflect.String: - offset := len(out) - out = appendU32(out, 0) - if n := field.Len(); n > 0 { - for j := 0; j < n; j++ { - f := field.Index(j) - if j != 0 { - out = append(out, ',') - } - out = append(out, f.String()...) - } - // overwrite length value - binary.BigEndian.PutUint32(out[offset:], uint32(len(out)-offset-4)) - } - default: - panic(fmt.Sprintf("slice of unknown type in field %d: %T", i, field.Interface())) - } - case reflect.Ptr: - if t == bigIntType { - var n *big.Int - nValue := reflect.ValueOf(&n) - nValue.Elem().Set(field) - needed := intLength(n) - oldLength := len(out) - - if cap(out)-len(out) < needed { - newOut := make([]byte, len(out), 2*(len(out)+needed)) - copy(newOut, out) - out = newOut - } - out = out[:oldLength+needed] - marshalInt(out[oldLength:], n) - } else { - panic(fmt.Sprintf("pointer to unknown type in field %d: %T", i, field.Interface())) - } - } - } - - return out -} - -var bigOne = big.NewInt(1) - -func parseString(in []byte) (out, rest []byte, ok bool) { - if len(in) < 4 { - return - } - length := binary.BigEndian.Uint32(in) - in = in[4:] - if uint32(len(in)) < length { - return - } - out = in[:length] - rest = in[length:] - ok = true - return -} - -var ( - comma = []byte{','} - emptyNameList = []string{} -) - -func parseNameList(in []byte) (out []string, rest []byte, ok bool) { - contents, rest, ok := parseString(in) - if !ok { - return - } - if len(contents) == 0 { - out = emptyNameList - return - } - parts := bytes.Split(contents, comma) - out = make([]string, len(parts)) - for i, part := range parts { - out[i] = string(part) - } - return -} - -func parseInt(in []byte) (out *big.Int, rest []byte, ok bool) { - contents, rest, ok := parseString(in) - if !ok { - return - } - out = new(big.Int) - - if len(contents) > 0 && contents[0]&0x80 == 0x80 { - // This is a negative number - notBytes := make([]byte, len(contents)) - for i := range notBytes { - notBytes[i] = ^contents[i] - } - out.SetBytes(notBytes) - out.Add(out, bigOne) - out.Neg(out) - } else { - // Positive number - out.SetBytes(contents) - } - ok = true - return -} - -func parseUint32(in []byte) (uint32, []byte, bool) { - if len(in) < 4 { - return 0, nil, false - } - return binary.BigEndian.Uint32(in), in[4:], true -} - -func parseUint64(in []byte) (uint64, []byte, bool) { - if len(in) < 8 { - return 0, nil, false - } - return binary.BigEndian.Uint64(in), in[8:], true -} - -func intLength(n *big.Int) int { - length := 4 /* length bytes */ - if n.Sign() < 0 { - nMinus1 := new(big.Int).Neg(n) - nMinus1.Sub(nMinus1, bigOne) - bitLen := nMinus1.BitLen() - if bitLen%8 == 0 { - // The number will need 0xff padding - length++ - } - length += (bitLen + 7) / 8 - } else if n.Sign() == 0 { - // A zero is the zero length string - } else { - bitLen := n.BitLen() - if bitLen%8 == 0 { - // The number will need 0x00 padding - length++ - } - length += (bitLen + 7) / 8 - } - - return length -} - -func marshalUint32(to []byte, n uint32) []byte { - binary.BigEndian.PutUint32(to, n) - return to[4:] -} - -func marshalUint64(to []byte, n uint64) []byte { - binary.BigEndian.PutUint64(to, n) - return to[8:] -} - -func marshalInt(to []byte, n *big.Int) []byte { - lengthBytes := to - to = to[4:] - length := 0 - - if n.Sign() < 0 { - // A negative number has to be converted to two's-complement - // form. So we'll subtract 1 and invert. If the - // most-significant-bit isn't set then we'll need to pad the - // beginning with 0xff in order to keep the number negative. - nMinus1 := new(big.Int).Neg(n) - nMinus1.Sub(nMinus1, bigOne) - bytes := nMinus1.Bytes() - for i := range bytes { - bytes[i] ^= 0xff - } - if len(bytes) == 0 || bytes[0]&0x80 == 0 { - to[0] = 0xff - to = to[1:] - length++ - } - nBytes := copy(to, bytes) - to = to[nBytes:] - length += nBytes - } else if n.Sign() == 0 { - // A zero is the zero length string - } else { - bytes := n.Bytes() - if len(bytes) > 0 && bytes[0]&0x80 != 0 { - // We'll have to pad this with a 0x00 in order to - // stop it looking like a negative number. - to[0] = 0 - to = to[1:] - length++ - } - nBytes := copy(to, bytes) - to = to[nBytes:] - length += nBytes - } - - lengthBytes[0] = byte(length >> 24) - lengthBytes[1] = byte(length >> 16) - lengthBytes[2] = byte(length >> 8) - lengthBytes[3] = byte(length) - return to -} - -func writeInt(w io.Writer, n *big.Int) { - length := intLength(n) - buf := make([]byte, length) - marshalInt(buf, n) - w.Write(buf) -} - -func writeString(w io.Writer, s []byte) { - var lengthBytes [4]byte - lengthBytes[0] = byte(len(s) >> 24) - lengthBytes[1] = byte(len(s) >> 16) - lengthBytes[2] = byte(len(s) >> 8) - lengthBytes[3] = byte(len(s)) - w.Write(lengthBytes[:]) - w.Write(s) -} - -func stringLength(n int) int { - return 4 + n -} - -func marshalString(to []byte, s []byte) []byte { - to[0] = byte(len(s) >> 24) - to[1] = byte(len(s) >> 16) - to[2] = byte(len(s) >> 8) - to[3] = byte(len(s)) - to = to[4:] - copy(to, s) - return to[len(s):] -} - -var bigIntType = reflect.TypeOf((*big.Int)(nil)) - -// Decode a packet into its corresponding message. -func decode(packet []byte) (interface{}, error) { - var msg interface{} - switch packet[0] { - case msgDisconnect: - msg = new(disconnectMsg) - case msgServiceRequest: - msg = new(serviceRequestMsg) - case msgServiceAccept: - msg = new(serviceAcceptMsg) - case msgKexInit: - msg = new(kexInitMsg) - case msgKexDHInit: - msg = new(kexDHInitMsg) - case msgKexDHReply: - msg = new(kexDHReplyMsg) - case msgUserAuthRequest: - msg = new(userAuthRequestMsg) - case msgUserAuthSuccess: - return new(userAuthSuccessMsg), nil - case msgUserAuthFailure: - msg = new(userAuthFailureMsg) - case msgUserAuthPubKeyOk: - msg = new(userAuthPubKeyOkMsg) - case msgGlobalRequest: - msg = new(globalRequestMsg) - case msgRequestSuccess: - msg = new(globalRequestSuccessMsg) - case msgRequestFailure: - msg = new(globalRequestFailureMsg) - case msgChannelOpen: - msg = new(channelOpenMsg) - case msgChannelData: - msg = new(channelDataMsg) - case msgChannelOpenConfirm: - msg = new(channelOpenConfirmMsg) - case msgChannelOpenFailure: - msg = new(channelOpenFailureMsg) - case msgChannelWindowAdjust: - msg = new(windowAdjustMsg) - case msgChannelEOF: - msg = new(channelEOFMsg) - case msgChannelClose: - msg = new(channelCloseMsg) - case msgChannelRequest: - msg = new(channelRequestMsg) - case msgChannelSuccess: - msg = new(channelRequestSuccessMsg) - case msgChannelFailure: - msg = new(channelRequestFailureMsg) - default: - return nil, unexpectedMessageError(0, packet[0]) - } - if err := Unmarshal(packet, msg); err != nil { - return nil, err - } - return msg, nil -} diff --git a/vendor/golang.org/x/crypto/ssh/mux.go b/vendor/golang.org/x/crypto/ssh/mux.go deleted file mode 100644 index f3a3ddd..0000000 --- a/vendor/golang.org/x/crypto/ssh/mux.go +++ /dev/null @@ -1,330 +0,0 @@ -// Copyright 2013 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 ssh - -import ( - "encoding/binary" - "fmt" - "io" - "log" - "sync" - "sync/atomic" -) - -// debugMux, if set, causes messages in the connection protocol to be -// logged. -const debugMux = false - -// chanList is a thread safe channel list. -type chanList struct { - // protects concurrent access to chans - sync.Mutex - - // chans are indexed by the local id of the channel, which the - // other side should send in the PeersId field. - chans []*channel - - // This is a debugging aid: it offsets all IDs by this - // amount. This helps distinguish otherwise identical - // server/client muxes - offset uint32 -} - -// Assigns a channel ID to the given channel. -func (c *chanList) add(ch *channel) uint32 { - c.Lock() - defer c.Unlock() - for i := range c.chans { - if c.chans[i] == nil { - c.chans[i] = ch - return uint32(i) + c.offset - } - } - c.chans = append(c.chans, ch) - return uint32(len(c.chans)-1) + c.offset -} - -// getChan returns the channel for the given ID. -func (c *chanList) getChan(id uint32) *channel { - id -= c.offset - - c.Lock() - defer c.Unlock() - if id < uint32(len(c.chans)) { - return c.chans[id] - } - return nil -} - -func (c *chanList) remove(id uint32) { - id -= c.offset - c.Lock() - if id < uint32(len(c.chans)) { - c.chans[id] = nil - } - c.Unlock() -} - -// dropAll forgets all channels it knows, returning them in a slice. -func (c *chanList) dropAll() []*channel { - c.Lock() - defer c.Unlock() - var r []*channel - - for _, ch := range c.chans { - if ch == nil { - continue - } - r = append(r, ch) - } - c.chans = nil - return r -} - -// mux represents the state for the SSH connection protocol, which -// multiplexes many channels onto a single packet transport. -type mux struct { - conn packetConn - chanList chanList - - incomingChannels chan NewChannel - - globalSentMu sync.Mutex - globalResponses chan interface{} - incomingRequests chan *Request - - errCond *sync.Cond - err error -} - -// When debugging, each new chanList instantiation has a different -// offset. -var globalOff uint32 - -func (m *mux) Wait() error { - m.errCond.L.Lock() - defer m.errCond.L.Unlock() - for m.err == nil { - m.errCond.Wait() - } - return m.err -} - -// newMux returns a mux that runs over the given connection. -func newMux(p packetConn) *mux { - m := &mux{ - conn: p, - incomingChannels: make(chan NewChannel, 16), - globalResponses: make(chan interface{}, 1), - incomingRequests: make(chan *Request, 16), - errCond: newCond(), - } - if debugMux { - m.chanList.offset = atomic.AddUint32(&globalOff, 1) - } - - go m.loop() - return m -} - -func (m *mux) sendMessage(msg interface{}) error { - p := Marshal(msg) - if debugMux { - log.Printf("send global(%d): %#v", m.chanList.offset, msg) - } - return m.conn.writePacket(p) -} - -func (m *mux) SendRequest(name string, wantReply bool, payload []byte) (bool, []byte, error) { - if wantReply { - m.globalSentMu.Lock() - defer m.globalSentMu.Unlock() - } - - if err := m.sendMessage(globalRequestMsg{ - Type: name, - WantReply: wantReply, - Data: payload, - }); err != nil { - return false, nil, err - } - - if !wantReply { - return false, nil, nil - } - - msg, ok := <-m.globalResponses - if !ok { - return false, nil, io.EOF - } - switch msg := msg.(type) { - case *globalRequestFailureMsg: - return false, msg.Data, nil - case *globalRequestSuccessMsg: - return true, msg.Data, nil - default: - return false, nil, fmt.Errorf("ssh: unexpected response to request: %#v", msg) - } -} - -// ackRequest must be called after processing a global request that -// has WantReply set. -func (m *mux) ackRequest(ok bool, data []byte) error { - if ok { - return m.sendMessage(globalRequestSuccessMsg{Data: data}) - } - return m.sendMessage(globalRequestFailureMsg{Data: data}) -} - -func (m *mux) Close() error { - return m.conn.Close() -} - -// loop runs the connection machine. It will process packets until an -// error is encountered. To synchronize on loop exit, use mux.Wait. -func (m *mux) loop() { - var err error - for err == nil { - err = m.onePacket() - } - - for _, ch := range m.chanList.dropAll() { - ch.close() - } - - close(m.incomingChannels) - close(m.incomingRequests) - close(m.globalResponses) - - m.conn.Close() - - m.errCond.L.Lock() - m.err = err - m.errCond.Broadcast() - m.errCond.L.Unlock() - - if debugMux { - log.Println("loop exit", err) - } -} - -// onePacket reads and processes one packet. -func (m *mux) onePacket() error { - packet, err := m.conn.readPacket() - if err != nil { - return err - } - - if debugMux { - if packet[0] == msgChannelData || packet[0] == msgChannelExtendedData { - log.Printf("decoding(%d): data packet - %d bytes", m.chanList.offset, len(packet)) - } else { - p, _ := decode(packet) - log.Printf("decoding(%d): %d %#v - %d bytes", m.chanList.offset, packet[0], p, len(packet)) - } - } - - switch packet[0] { - case msgChannelOpen: - return m.handleChannelOpen(packet) - case msgGlobalRequest, msgRequestSuccess, msgRequestFailure: - return m.handleGlobalPacket(packet) - } - - // assume a channel packet. - if len(packet) < 5 { - return parseError(packet[0]) - } - id := binary.BigEndian.Uint32(packet[1:]) - ch := m.chanList.getChan(id) - if ch == nil { - return fmt.Errorf("ssh: invalid channel %d", id) - } - - return ch.handlePacket(packet) -} - -func (m *mux) handleGlobalPacket(packet []byte) error { - msg, err := decode(packet) - if err != nil { - return err - } - - switch msg := msg.(type) { - case *globalRequestMsg: - m.incomingRequests <- &Request{ - Type: msg.Type, - WantReply: msg.WantReply, - Payload: msg.Data, - mux: m, - } - case *globalRequestSuccessMsg, *globalRequestFailureMsg: - m.globalResponses <- msg - default: - panic(fmt.Sprintf("not a global message %#v", msg)) - } - - return nil -} - -// handleChannelOpen schedules a channel to be Accept()ed. -func (m *mux) handleChannelOpen(packet []byte) error { - var msg channelOpenMsg - if err := Unmarshal(packet, &msg); err != nil { - return err - } - - if msg.MaxPacketSize < minPacketLength || msg.MaxPacketSize > 1<<31 { - failMsg := channelOpenFailureMsg{ - PeersId: msg.PeersId, - Reason: ConnectionFailed, - Message: "invalid request", - Language: "en_US.UTF-8", - } - return m.sendMessage(failMsg) - } - - c := m.newChannel(msg.ChanType, channelInbound, msg.TypeSpecificData) - c.remoteId = msg.PeersId - c.maxRemotePayload = msg.MaxPacketSize - c.remoteWin.add(msg.PeersWindow) - m.incomingChannels <- c - return nil -} - -func (m *mux) OpenChannel(chanType string, extra []byte) (Channel, <-chan *Request, error) { - ch, err := m.openChannel(chanType, extra) - if err != nil { - return nil, nil, err - } - - return ch, ch.incomingRequests, nil -} - -func (m *mux) openChannel(chanType string, extra []byte) (*channel, error) { - ch := m.newChannel(chanType, channelOutbound, extra) - - ch.maxIncomingPayload = channelMaxPacket - - open := channelOpenMsg{ - ChanType: chanType, - PeersWindow: ch.myWindow, - MaxPacketSize: ch.maxIncomingPayload, - TypeSpecificData: extra, - PeersId: ch.localId, - } - if err := m.sendMessage(open); err != nil { - return nil, err - } - - switch msg := (<-ch.msg).(type) { - case *channelOpenConfirmMsg: - return ch, nil - case *channelOpenFailureMsg: - return nil, &OpenChannelError{msg.Reason, msg.Message} - default: - return nil, fmt.Errorf("ssh: unexpected packet in response to channel open: %T", msg) - } -} diff --git a/vendor/golang.org/x/crypto/ssh/server.go b/vendor/golang.org/x/crypto/ssh/server.go deleted file mode 100644 index 37df1b3..0000000 --- a/vendor/golang.org/x/crypto/ssh/server.go +++ /dev/null @@ -1,488 +0,0 @@ -// Copyright 2011 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 ssh - -import ( - "bytes" - "errors" - "fmt" - "io" - "net" -) - -// The Permissions type holds fine-grained permissions that are -// specific to a user or a specific authentication method for a -// user. Permissions, except for "source-address", must be enforced in -// the server application layer, after successful authentication. The -// Permissions are passed on in ServerConn so a server implementation -// can honor them. -type Permissions struct { - // Critical options restrict default permissions. Common - // restrictions are "source-address" and "force-command". If - // the server cannot enforce the restriction, or does not - // recognize it, the user should not authenticate. - CriticalOptions map[string]string - - // Extensions are extra functionality that the server may - // offer on authenticated connections. Common extensions are - // "permit-agent-forwarding", "permit-X11-forwarding". Lack of - // support for an extension does not preclude authenticating a - // user. - Extensions map[string]string -} - -// ServerConfig holds server specific configuration data. -type ServerConfig struct { - // Config contains configuration shared between client and server. - Config - - hostKeys []Signer - - // NoClientAuth is true if clients are allowed to connect without - // authenticating. - NoClientAuth bool - - // PasswordCallback, if non-nil, is called when a user - // attempts to authenticate using a password. - PasswordCallback func(conn ConnMetadata, password []byte) (*Permissions, error) - - // PublicKeyCallback, if non-nil, is called when a client attempts public - // key authentication. It must return true if the given public key is - // valid for the given user. For example, see CertChecker.Authenticate. - PublicKeyCallback func(conn ConnMetadata, key PublicKey) (*Permissions, error) - - // KeyboardInteractiveCallback, if non-nil, is called when - // keyboard-interactive authentication is selected (RFC - // 4256). The client object's Challenge function should be - // used to query the user. The callback may offer multiple - // Challenge rounds. To avoid information leaks, the client - // should be presented a challenge even if the user is - // unknown. - KeyboardInteractiveCallback func(conn ConnMetadata, client KeyboardInteractiveChallenge) (*Permissions, error) - - // AuthLogCallback, if non-nil, is called to log all authentication - // attempts. - AuthLogCallback func(conn ConnMetadata, method string, err error) - - // ServerVersion is the version identification string to announce in - // the public handshake. - // If empty, a reasonable default is used. - // Note that RFC 4253 section 4.2 requires that this string start with - // "SSH-2.0-". - ServerVersion string -} - -// AddHostKey adds a private key as a host key. If an existing host -// key exists with the same algorithm, it is overwritten. Each server -// config must have at least one host key. -func (s *ServerConfig) AddHostKey(key Signer) { - for i, k := range s.hostKeys { - if k.PublicKey().Type() == key.PublicKey().Type() { - s.hostKeys[i] = key - return - } - } - - s.hostKeys = append(s.hostKeys, key) -} - -// cachedPubKey contains the results of querying whether a public key is -// acceptable for a user. -type cachedPubKey struct { - user string - pubKeyData []byte - result error - perms *Permissions -} - -const maxCachedPubKeys = 16 - -// pubKeyCache caches tests for public keys. Since SSH clients -// will query whether a public key is acceptable before attempting to -// authenticate with it, we end up with duplicate queries for public -// key validity. The cache only applies to a single ServerConn. -type pubKeyCache struct { - keys []cachedPubKey -} - -// get returns the result for a given user/algo/key tuple. -func (c *pubKeyCache) get(user string, pubKeyData []byte) (cachedPubKey, bool) { - for _, k := range c.keys { - if k.user == user && bytes.Equal(k.pubKeyData, pubKeyData) { - return k, true - } - } - return cachedPubKey{}, false -} - -// add adds the given tuple to the cache. -func (c *pubKeyCache) add(candidate cachedPubKey) { - if len(c.keys) < maxCachedPubKeys { - c.keys = append(c.keys, candidate) - } -} - -// ServerConn is an authenticated SSH connection, as seen from the -// server -type ServerConn struct { - Conn - - // If the succeeding authentication callback returned a - // non-nil Permissions pointer, it is stored here. - Permissions *Permissions -} - -// NewServerConn starts a new SSH server with c as the underlying -// transport. It starts with a handshake and, if the handshake is -// unsuccessful, it closes the connection and returns an error. The -// Request and NewChannel channels must be serviced, or the connection -// will hang. -func NewServerConn(c net.Conn, config *ServerConfig) (*ServerConn, <-chan NewChannel, <-chan *Request, error) { - fullConf := *config - fullConf.SetDefaults() - s := &connection{ - sshConn: sshConn{conn: c}, - } - perms, err := s.serverHandshake(&fullConf) - if err != nil { - c.Close() - return nil, nil, nil, err - } - return &ServerConn{s, perms}, s.mux.incomingChannels, s.mux.incomingRequests, nil -} - -// signAndMarshal signs the data with the appropriate algorithm, -// and serializes the result in SSH wire format. -func signAndMarshal(k Signer, rand io.Reader, data []byte) ([]byte, error) { - sig, err := k.Sign(rand, data) - if err != nil { - return nil, err - } - - return Marshal(sig), nil -} - -// handshake performs key exchange and user authentication. -func (s *connection) serverHandshake(config *ServerConfig) (*Permissions, error) { - if len(config.hostKeys) == 0 { - return nil, errors.New("ssh: server has no host keys") - } - - if !config.NoClientAuth && config.PasswordCallback == nil && config.PublicKeyCallback == nil && config.KeyboardInteractiveCallback == nil { - return nil, errors.New("ssh: no authentication methods configured but NoClientAuth is also false") - } - - if config.ServerVersion != "" { - s.serverVersion = []byte(config.ServerVersion) - } else { - s.serverVersion = []byte(packageVersion) - } - var err error - s.clientVersion, err = exchangeVersions(s.sshConn.conn, s.serverVersion) - if err != nil { - return nil, err - } - - tr := newTransport(s.sshConn.conn, config.Rand, false /* not client */) - s.transport = newServerTransport(tr, s.clientVersion, s.serverVersion, config) - - if err := s.transport.requestInitialKeyChange(); err != nil { - return nil, err - } - - // We just did the key change, so the session ID is established. - s.sessionID = s.transport.getSessionID() - - var packet []byte - if packet, err = s.transport.readPacket(); err != nil { - return nil, err - } - - var serviceRequest serviceRequestMsg - if err = Unmarshal(packet, &serviceRequest); err != nil { - return nil, err - } - if serviceRequest.Service != serviceUserAuth { - return nil, errors.New("ssh: requested service '" + serviceRequest.Service + "' before authenticating") - } - serviceAccept := serviceAcceptMsg{ - Service: serviceUserAuth, - } - if err := s.transport.writePacket(Marshal(&serviceAccept)); err != nil { - return nil, err - } - - perms, err := s.serverAuthenticate(config) - if err != nil { - return nil, err - } - s.mux = newMux(s.transport) - return perms, err -} - -func isAcceptableAlgo(algo string) bool { - switch algo { - case KeyAlgoRSA, KeyAlgoDSA, KeyAlgoECDSA256, KeyAlgoECDSA384, KeyAlgoECDSA521, KeyAlgoED25519, - CertAlgoRSAv01, CertAlgoDSAv01, CertAlgoECDSA256v01, CertAlgoECDSA384v01, CertAlgoECDSA521v01: - return true - } - return false -} - -func checkSourceAddress(addr net.Addr, sourceAddr string) error { - if addr == nil { - return errors.New("ssh: no address known for client, but source-address match required") - } - - tcpAddr, ok := addr.(*net.TCPAddr) - if !ok { - return fmt.Errorf("ssh: remote address %v is not an TCP address when checking source-address match", addr) - } - - if allowedIP := net.ParseIP(sourceAddr); allowedIP != nil { - if bytes.Equal(allowedIP, tcpAddr.IP) { - return nil - } - } else { - _, ipNet, err := net.ParseCIDR(sourceAddr) - if err != nil { - return fmt.Errorf("ssh: error parsing source-address restriction %q: %v", sourceAddr, err) - } - - if ipNet.Contains(tcpAddr.IP) { - return nil - } - } - - return fmt.Errorf("ssh: remote address %v is not allowed because of source-address restriction", addr) -} - -func (s *connection) serverAuthenticate(config *ServerConfig) (*Permissions, error) { - var err error - var cache pubKeyCache - var perms *Permissions - -userAuthLoop: - for { - var userAuthReq userAuthRequestMsg - if packet, err := s.transport.readPacket(); err != nil { - return nil, err - } else if err = Unmarshal(packet, &userAuthReq); err != nil { - return nil, err - } - - if userAuthReq.Service != serviceSSH { - return nil, errors.New("ssh: client attempted to negotiate for unknown service: " + userAuthReq.Service) - } - - s.user = userAuthReq.User - perms = nil - authErr := errors.New("no auth passed yet") - - switch userAuthReq.Method { - case "none": - if config.NoClientAuth { - authErr = nil - } - case "password": - if config.PasswordCallback == nil { - authErr = errors.New("ssh: password auth not configured") - break - } - payload := userAuthReq.Payload - if len(payload) < 1 || payload[0] != 0 { - return nil, parseError(msgUserAuthRequest) - } - payload = payload[1:] - password, payload, ok := parseString(payload) - if !ok || len(payload) > 0 { - return nil, parseError(msgUserAuthRequest) - } - - perms, authErr = config.PasswordCallback(s, password) - case "keyboard-interactive": - if config.KeyboardInteractiveCallback == nil { - authErr = errors.New("ssh: keyboard-interactive auth not configubred") - break - } - - prompter := &sshClientKeyboardInteractive{s} - perms, authErr = config.KeyboardInteractiveCallback(s, prompter.Challenge) - case "publickey": - if config.PublicKeyCallback == nil { - authErr = errors.New("ssh: publickey auth not configured") - break - } - payload := userAuthReq.Payload - if len(payload) < 1 { - return nil, parseError(msgUserAuthRequest) - } - isQuery := payload[0] == 0 - payload = payload[1:] - algoBytes, payload, ok := parseString(payload) - if !ok { - return nil, parseError(msgUserAuthRequest) - } - algo := string(algoBytes) - if !isAcceptableAlgo(algo) { - authErr = fmt.Errorf("ssh: algorithm %q not accepted", algo) - break - } - - pubKeyData, payload, ok := parseString(payload) - if !ok { - return nil, parseError(msgUserAuthRequest) - } - - pubKey, err := ParsePublicKey(pubKeyData) - if err != nil { - return nil, err - } - - candidate, ok := cache.get(s.user, pubKeyData) - if !ok { - candidate.user = s.user - candidate.pubKeyData = pubKeyData - candidate.perms, candidate.result = config.PublicKeyCallback(s, pubKey) - if candidate.result == nil && candidate.perms != nil && candidate.perms.CriticalOptions != nil && candidate.perms.CriticalOptions[sourceAddressCriticalOption] != "" { - candidate.result = checkSourceAddress( - s.RemoteAddr(), - candidate.perms.CriticalOptions[sourceAddressCriticalOption]) - } - cache.add(candidate) - } - - if isQuery { - // The client can query if the given public key - // would be okay. - if len(payload) > 0 { - return nil, parseError(msgUserAuthRequest) - } - - if candidate.result == nil { - okMsg := userAuthPubKeyOkMsg{ - Algo: algo, - PubKey: pubKeyData, - } - if err = s.transport.writePacket(Marshal(&okMsg)); err != nil { - return nil, err - } - continue userAuthLoop - } - authErr = candidate.result - } else { - sig, payload, ok := parseSignature(payload) - if !ok || len(payload) > 0 { - return nil, parseError(msgUserAuthRequest) - } - // Ensure the public key algo and signature algo - // are supported. Compare the private key - // algorithm name that corresponds to algo with - // sig.Format. This is usually the same, but - // for certs, the names differ. - if !isAcceptableAlgo(sig.Format) { - break - } - signedData := buildDataSignedForAuth(s.transport.getSessionID(), userAuthReq, algoBytes, pubKeyData) - - if err := pubKey.Verify(signedData, sig); err != nil { - return nil, err - } - - authErr = candidate.result - perms = candidate.perms - } - default: - authErr = fmt.Errorf("ssh: unknown method %q", userAuthReq.Method) - } - - if config.AuthLogCallback != nil { - config.AuthLogCallback(s, userAuthReq.Method, authErr) - } - - if authErr == nil { - break userAuthLoop - } - - var failureMsg userAuthFailureMsg - if config.PasswordCallback != nil { - failureMsg.Methods = append(failureMsg.Methods, "password") - } - if config.PublicKeyCallback != nil { - failureMsg.Methods = append(failureMsg.Methods, "publickey") - } - if config.KeyboardInteractiveCallback != nil { - failureMsg.Methods = append(failureMsg.Methods, "keyboard-interactive") - } - - if len(failureMsg.Methods) == 0 { - return nil, errors.New("ssh: no authentication methods configured but NoClientAuth is also false") - } - - if err = s.transport.writePacket(Marshal(&failureMsg)); err != nil { - return nil, err - } - } - - if err = s.transport.writePacket([]byte{msgUserAuthSuccess}); err != nil { - return nil, err - } - return perms, nil -} - -// sshClientKeyboardInteractive implements a ClientKeyboardInteractive by -// asking the client on the other side of a ServerConn. -type sshClientKeyboardInteractive struct { - *connection -} - -func (c *sshClientKeyboardInteractive) Challenge(user, instruction string, questions []string, echos []bool) (answers []string, err error) { - if len(questions) != len(echos) { - return nil, errors.New("ssh: echos and questions must have equal length") - } - - var prompts []byte - for i := range questions { - prompts = appendString(prompts, questions[i]) - prompts = appendBool(prompts, echos[i]) - } - - if err := c.transport.writePacket(Marshal(&userAuthInfoRequestMsg{ - Instruction: instruction, - NumPrompts: uint32(len(questions)), - Prompts: prompts, - })); err != nil { - return nil, err - } - - packet, err := c.transport.readPacket() - if err != nil { - return nil, err - } - if packet[0] != msgUserAuthInfoResponse { - return nil, unexpectedMessageError(msgUserAuthInfoResponse, packet[0]) - } - packet = packet[1:] - - n, packet, ok := parseUint32(packet) - if !ok || int(n) != len(questions) { - return nil, parseError(msgUserAuthInfoResponse) - } - - for i := uint32(0); i < n; i++ { - ans, rest, ok := parseString(packet) - if !ok { - return nil, parseError(msgUserAuthInfoResponse) - } - - answers = append(answers, string(ans)) - packet = rest - } - if len(packet) != 0 { - return nil, errors.New("ssh: junk at end of message") - } - - return answers, nil -} diff --git a/vendor/golang.org/x/crypto/ssh/session.go b/vendor/golang.org/x/crypto/ssh/session.go deleted file mode 100644 index 17e2aa8..0000000 --- a/vendor/golang.org/x/crypto/ssh/session.go +++ /dev/null @@ -1,627 +0,0 @@ -// Copyright 2011 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 ssh - -// Session implements an interactive session described in -// "RFC 4254, section 6". - -import ( - "bytes" - "encoding/binary" - "errors" - "fmt" - "io" - "io/ioutil" - "sync" -) - -type Signal string - -// POSIX signals as listed in RFC 4254 Section 6.10. -const ( - SIGABRT Signal = "ABRT" - SIGALRM Signal = "ALRM" - SIGFPE Signal = "FPE" - SIGHUP Signal = "HUP" - SIGILL Signal = "ILL" - SIGINT Signal = "INT" - SIGKILL Signal = "KILL" - SIGPIPE Signal = "PIPE" - SIGQUIT Signal = "QUIT" - SIGSEGV Signal = "SEGV" - SIGTERM Signal = "TERM" - SIGUSR1 Signal = "USR1" - SIGUSR2 Signal = "USR2" -) - -var signals = map[Signal]int{ - SIGABRT: 6, - SIGALRM: 14, - SIGFPE: 8, - SIGHUP: 1, - SIGILL: 4, - SIGINT: 2, - SIGKILL: 9, - SIGPIPE: 13, - SIGQUIT: 3, - SIGSEGV: 11, - SIGTERM: 15, -} - -type TerminalModes map[uint8]uint32 - -// POSIX terminal mode flags as listed in RFC 4254 Section 8. -const ( - tty_OP_END = 0 - VINTR = 1 - VQUIT = 2 - VERASE = 3 - VKILL = 4 - VEOF = 5 - VEOL = 6 - VEOL2 = 7 - VSTART = 8 - VSTOP = 9 - VSUSP = 10 - VDSUSP = 11 - VREPRINT = 12 - VWERASE = 13 - VLNEXT = 14 - VFLUSH = 15 - VSWTCH = 16 - VSTATUS = 17 - VDISCARD = 18 - IGNPAR = 30 - PARMRK = 31 - INPCK = 32 - ISTRIP = 33 - INLCR = 34 - IGNCR = 35 - ICRNL = 36 - IUCLC = 37 - IXON = 38 - IXANY = 39 - IXOFF = 40 - IMAXBEL = 41 - ISIG = 50 - ICANON = 51 - XCASE = 52 - ECHO = 53 - ECHOE = 54 - ECHOK = 55 - ECHONL = 56 - NOFLSH = 57 - TOSTOP = 58 - IEXTEN = 59 - ECHOCTL = 60 - ECHOKE = 61 - PENDIN = 62 - OPOST = 70 - OLCUC = 71 - ONLCR = 72 - OCRNL = 73 - ONOCR = 74 - ONLRET = 75 - CS7 = 90 - CS8 = 91 - PARENB = 92 - PARODD = 93 - TTY_OP_ISPEED = 128 - TTY_OP_OSPEED = 129 -) - -// A Session represents a connection to a remote command or shell. -type Session struct { - // Stdin specifies the remote process's standard input. - // If Stdin is nil, the remote process reads from an empty - // bytes.Buffer. - Stdin io.Reader - - // Stdout and Stderr specify the remote process's standard - // output and error. - // - // If either is nil, Run connects the corresponding file - // descriptor to an instance of ioutil.Discard. There is a - // fixed amount of buffering that is shared for the two streams. - // If either blocks it may eventually cause the remote - // command to block. - Stdout io.Writer - Stderr io.Writer - - ch Channel // the channel backing this session - started bool // true once Start, Run or Shell is invoked. - copyFuncs []func() error - errors chan error // one send per copyFunc - - // true if pipe method is active - stdinpipe, stdoutpipe, stderrpipe bool - - // stdinPipeWriter is non-nil if StdinPipe has not been called - // and Stdin was specified by the user; it is the write end of - // a pipe connecting Session.Stdin to the stdin channel. - stdinPipeWriter io.WriteCloser - - exitStatus chan error -} - -// SendRequest sends an out-of-band channel request on the SSH channel -// underlying the session. -func (s *Session) SendRequest(name string, wantReply bool, payload []byte) (bool, error) { - return s.ch.SendRequest(name, wantReply, payload) -} - -func (s *Session) Close() error { - return s.ch.Close() -} - -// RFC 4254 Section 6.4. -type setenvRequest struct { - Name string - Value string -} - -// Setenv sets an environment variable that will be applied to any -// command executed by Shell or Run. -func (s *Session) Setenv(name, value string) error { - msg := setenvRequest{ - Name: name, - Value: value, - } - ok, err := s.ch.SendRequest("env", true, Marshal(&msg)) - if err == nil && !ok { - err = errors.New("ssh: setenv failed") - } - return err -} - -// RFC 4254 Section 6.2. -type ptyRequestMsg struct { - Term string - Columns uint32 - Rows uint32 - Width uint32 - Height uint32 - Modelist string -} - -// RequestPty requests the association of a pty with the session on the remote host. -func (s *Session) RequestPty(term string, h, w int, termmodes TerminalModes) error { - var tm []byte - for k, v := range termmodes { - kv := struct { - Key byte - Val uint32 - }{k, v} - - tm = append(tm, Marshal(&kv)...) - } - tm = append(tm, tty_OP_END) - req := ptyRequestMsg{ - Term: term, - Columns: uint32(w), - Rows: uint32(h), - Width: uint32(w * 8), - Height: uint32(h * 8), - Modelist: string(tm), - } - ok, err := s.ch.SendRequest("pty-req", true, Marshal(&req)) - if err == nil && !ok { - err = errors.New("ssh: pty-req failed") - } - return err -} - -// RFC 4254 Section 6.5. -type subsystemRequestMsg struct { - Subsystem string -} - -// RequestSubsystem requests the association of a subsystem with the session on the remote host. -// A subsystem is a predefined command that runs in the background when the ssh session is initiated -func (s *Session) RequestSubsystem(subsystem string) error { - msg := subsystemRequestMsg{ - Subsystem: subsystem, - } - ok, err := s.ch.SendRequest("subsystem", true, Marshal(&msg)) - if err == nil && !ok { - err = errors.New("ssh: subsystem request failed") - } - return err -} - -// RFC 4254 Section 6.9. -type signalMsg struct { - Signal string -} - -// Signal sends the given signal to the remote process. -// sig is one of the SIG* constants. -func (s *Session) Signal(sig Signal) error { - msg := signalMsg{ - Signal: string(sig), - } - - _, err := s.ch.SendRequest("signal", false, Marshal(&msg)) - return err -} - -// RFC 4254 Section 6.5. -type execMsg struct { - Command string -} - -// Start runs cmd on the remote host. Typically, the remote -// server passes cmd to the shell for interpretation. -// A Session only accepts one call to Run, Start or Shell. -func (s *Session) Start(cmd string) error { - if s.started { - return errors.New("ssh: session already started") - } - req := execMsg{ - Command: cmd, - } - - ok, err := s.ch.SendRequest("exec", true, Marshal(&req)) - if err == nil && !ok { - err = fmt.Errorf("ssh: command %v failed", cmd) - } - if err != nil { - return err - } - return s.start() -} - -// Run runs cmd on the remote host. Typically, the remote -// server passes cmd to the shell for interpretation. -// A Session only accepts one call to Run, Start, Shell, Output, -// or CombinedOutput. -// -// The returned error is nil if the command runs, has no problems -// copying stdin, stdout, and stderr, and exits with a zero exit -// status. -// -// If the remote server does not send an exit status, an error of type -// *ExitMissingError is returned. If the command completes -// unsuccessfully or is interrupted by a signal, the error is of type -// *ExitError. Other error types may be returned for I/O problems. -func (s *Session) Run(cmd string) error { - err := s.Start(cmd) - if err != nil { - return err - } - return s.Wait() -} - -// Output runs cmd on the remote host and returns its standard output. -func (s *Session) Output(cmd string) ([]byte, error) { - if s.Stdout != nil { - return nil, errors.New("ssh: Stdout already set") - } - var b bytes.Buffer - s.Stdout = &b - err := s.Run(cmd) - return b.Bytes(), err -} - -type singleWriter struct { - b bytes.Buffer - mu sync.Mutex -} - -func (w *singleWriter) Write(p []byte) (int, error) { - w.mu.Lock() - defer w.mu.Unlock() - return w.b.Write(p) -} - -// CombinedOutput runs cmd on the remote host and returns its combined -// standard output and standard error. -func (s *Session) CombinedOutput(cmd string) ([]byte, error) { - if s.Stdout != nil { - return nil, errors.New("ssh: Stdout already set") - } - if s.Stderr != nil { - return nil, errors.New("ssh: Stderr already set") - } - var b singleWriter - s.Stdout = &b - s.Stderr = &b - err := s.Run(cmd) - return b.b.Bytes(), err -} - -// Shell starts a login shell on the remote host. A Session only -// accepts one call to Run, Start, Shell, Output, or CombinedOutput. -func (s *Session) Shell() error { - if s.started { - return errors.New("ssh: session already started") - } - - ok, err := s.ch.SendRequest("shell", true, nil) - if err == nil && !ok { - return errors.New("ssh: could not start shell") - } - if err != nil { - return err - } - return s.start() -} - -func (s *Session) start() error { - s.started = true - - type F func(*Session) - for _, setupFd := range []F{(*Session).stdin, (*Session).stdout, (*Session).stderr} { - setupFd(s) - } - - s.errors = make(chan error, len(s.copyFuncs)) - for _, fn := range s.copyFuncs { - go func(fn func() error) { - s.errors <- fn() - }(fn) - } - return nil -} - -// Wait waits for the remote command to exit. -// -// The returned error is nil if the command runs, has no problems -// copying stdin, stdout, and stderr, and exits with a zero exit -// status. -// -// If the remote server does not send an exit status, an error of type -// *ExitMissingError is returned. If the command completes -// unsuccessfully or is interrupted by a signal, the error is of type -// *ExitError. Other error types may be returned for I/O problems. -func (s *Session) Wait() error { - if !s.started { - return errors.New("ssh: session not started") - } - waitErr := <-s.exitStatus - - if s.stdinPipeWriter != nil { - s.stdinPipeWriter.Close() - } - var copyError error - for _ = range s.copyFuncs { - if err := <-s.errors; err != nil && copyError == nil { - copyError = err - } - } - if waitErr != nil { - return waitErr - } - return copyError -} - -func (s *Session) wait(reqs <-chan *Request) error { - wm := Waitmsg{status: -1} - // Wait for msg channel to be closed before returning. - for msg := range reqs { - switch msg.Type { - case "exit-status": - wm.status = int(binary.BigEndian.Uint32(msg.Payload)) - case "exit-signal": - var sigval struct { - Signal string - CoreDumped bool - Error string - Lang string - } - if err := Unmarshal(msg.Payload, &sigval); err != nil { - return err - } - - // Must sanitize strings? - wm.signal = sigval.Signal - wm.msg = sigval.Error - wm.lang = sigval.Lang - default: - // This handles keepalives and matches - // OpenSSH's behaviour. - if msg.WantReply { - msg.Reply(false, nil) - } - } - } - if wm.status == 0 { - return nil - } - if wm.status == -1 { - // exit-status was never sent from server - if wm.signal == "" { - // signal was not sent either. RFC 4254 - // section 6.10 recommends against this - // behavior, but it is allowed, so we let - // clients handle it. - return &ExitMissingError{} - } - wm.status = 128 - if _, ok := signals[Signal(wm.signal)]; ok { - wm.status += signals[Signal(wm.signal)] - } - } - - return &ExitError{wm} -} - -// ExitMissingError is returned if a session is torn down cleanly, but -// the server sends no confirmation of the exit status. -type ExitMissingError struct{} - -func (e *ExitMissingError) Error() string { - return "wait: remote command exited without exit status or exit signal" -} - -func (s *Session) stdin() { - if s.stdinpipe { - return - } - var stdin io.Reader - if s.Stdin == nil { - stdin = new(bytes.Buffer) - } else { - r, w := io.Pipe() - go func() { - _, err := io.Copy(w, s.Stdin) - w.CloseWithError(err) - }() - stdin, s.stdinPipeWriter = r, w - } - s.copyFuncs = append(s.copyFuncs, func() error { - _, err := io.Copy(s.ch, stdin) - if err1 := s.ch.CloseWrite(); err == nil && err1 != io.EOF { - err = err1 - } - return err - }) -} - -func (s *Session) stdout() { - if s.stdoutpipe { - return - } - if s.Stdout == nil { - s.Stdout = ioutil.Discard - } - s.copyFuncs = append(s.copyFuncs, func() error { - _, err := io.Copy(s.Stdout, s.ch) - return err - }) -} - -func (s *Session) stderr() { - if s.stderrpipe { - return - } - if s.Stderr == nil { - s.Stderr = ioutil.Discard - } - s.copyFuncs = append(s.copyFuncs, func() error { - _, err := io.Copy(s.Stderr, s.ch.Stderr()) - return err - }) -} - -// sessionStdin reroutes Close to CloseWrite. -type sessionStdin struct { - io.Writer - ch Channel -} - -func (s *sessionStdin) Close() error { - return s.ch.CloseWrite() -} - -// StdinPipe returns a pipe that will be connected to the -// remote command's standard input when the command starts. -func (s *Session) StdinPipe() (io.WriteCloser, error) { - if s.Stdin != nil { - return nil, errors.New("ssh: Stdin already set") - } - if s.started { - return nil, errors.New("ssh: StdinPipe after process started") - } - s.stdinpipe = true - return &sessionStdin{s.ch, s.ch}, nil -} - -// StdoutPipe returns a pipe that will be connected to the -// remote command's standard output when the command starts. -// There is a fixed amount of buffering that is shared between -// stdout and stderr streams. If the StdoutPipe reader is -// not serviced fast enough it may eventually cause the -// remote command to block. -func (s *Session) StdoutPipe() (io.Reader, error) { - if s.Stdout != nil { - return nil, errors.New("ssh: Stdout already set") - } - if s.started { - return nil, errors.New("ssh: StdoutPipe after process started") - } - s.stdoutpipe = true - return s.ch, nil -} - -// StderrPipe returns a pipe that will be connected to the -// remote command's standard error when the command starts. -// There is a fixed amount of buffering that is shared between -// stdout and stderr streams. If the StderrPipe reader is -// not serviced fast enough it may eventually cause the -// remote command to block. -func (s *Session) StderrPipe() (io.Reader, error) { - if s.Stderr != nil { - return nil, errors.New("ssh: Stderr already set") - } - if s.started { - return nil, errors.New("ssh: StderrPipe after process started") - } - s.stderrpipe = true - return s.ch.Stderr(), nil -} - -// newSession returns a new interactive session on the remote host. -func newSession(ch Channel, reqs <-chan *Request) (*Session, error) { - s := &Session{ - ch: ch, - } - s.exitStatus = make(chan error, 1) - go func() { - s.exitStatus <- s.wait(reqs) - }() - - return s, nil -} - -// An ExitError reports unsuccessful completion of a remote command. -type ExitError struct { - Waitmsg -} - -func (e *ExitError) Error() string { - return e.Waitmsg.String() -} - -// Waitmsg stores the information about an exited remote command -// as reported by Wait. -type Waitmsg struct { - status int - signal string - msg string - lang string -} - -// ExitStatus returns the exit status of the remote command. -func (w Waitmsg) ExitStatus() int { - return w.status -} - -// Signal returns the exit signal of the remote command if -// it was terminated violently. -func (w Waitmsg) Signal() string { - return w.signal -} - -// Msg returns the exit message given by the remote command -func (w Waitmsg) Msg() string { - return w.msg -} - -// Lang returns the language tag. See RFC 3066 -func (w Waitmsg) Lang() string { - return w.lang -} - -func (w Waitmsg) String() string { - str := fmt.Sprintf("Process exited with status %v", w.status) - if w.signal != "" { - str += fmt.Sprintf(" from signal %v", w.signal) - } - if w.msg != "" { - str += fmt.Sprintf(". Reason was: %v", w.msg) - } - return str -} diff --git a/vendor/golang.org/x/crypto/ssh/tcpip.go b/vendor/golang.org/x/crypto/ssh/tcpip.go deleted file mode 100644 index 6151241..0000000 --- a/vendor/golang.org/x/crypto/ssh/tcpip.go +++ /dev/null @@ -1,407 +0,0 @@ -// Copyright 2011 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 ssh - -import ( - "errors" - "fmt" - "io" - "math/rand" - "net" - "strconv" - "strings" - "sync" - "time" -) - -// Listen requests the remote peer open a listening socket on -// addr. Incoming connections will be available by calling Accept on -// the returned net.Listener. The listener must be serviced, or the -// SSH connection may hang. -func (c *Client) Listen(n, addr string) (net.Listener, error) { - laddr, err := net.ResolveTCPAddr(n, addr) - if err != nil { - return nil, err - } - return c.ListenTCP(laddr) -} - -// Automatic port allocation is broken with OpenSSH before 6.0. See -// also https://bugzilla.mindrot.org/show_bug.cgi?id=2017. In -// particular, OpenSSH 5.9 sends a channelOpenMsg with port number 0, -// rather than the actual port number. This means you can never open -// two different listeners with auto allocated ports. We work around -// this by trying explicit ports until we succeed. - -const openSSHPrefix = "OpenSSH_" - -var portRandomizer = rand.New(rand.NewSource(time.Now().UnixNano())) - -// isBrokenOpenSSHVersion returns true if the given version string -// specifies a version of OpenSSH that is known to have a bug in port -// forwarding. -func isBrokenOpenSSHVersion(versionStr string) bool { - i := strings.Index(versionStr, openSSHPrefix) - if i < 0 { - return false - } - i += len(openSSHPrefix) - j := i - for ; j < len(versionStr); j++ { - if versionStr[j] < '0' || versionStr[j] > '9' { - break - } - } - version, _ := strconv.Atoi(versionStr[i:j]) - return version < 6 -} - -// autoPortListenWorkaround simulates automatic port allocation by -// trying random ports repeatedly. -func (c *Client) autoPortListenWorkaround(laddr *net.TCPAddr) (net.Listener, error) { - var sshListener net.Listener - var err error - const tries = 10 - for i := 0; i < tries; i++ { - addr := *laddr - addr.Port = 1024 + portRandomizer.Intn(60000) - sshListener, err = c.ListenTCP(&addr) - if err == nil { - laddr.Port = addr.Port - return sshListener, err - } - } - return nil, fmt.Errorf("ssh: listen on random port failed after %d tries: %v", tries, err) -} - -// RFC 4254 7.1 -type channelForwardMsg struct { - addr string - rport uint32 -} - -// ListenTCP requests the remote peer open a listening socket -// on laddr. Incoming connections will be available by calling -// Accept on the returned net.Listener. -func (c *Client) ListenTCP(laddr *net.TCPAddr) (net.Listener, error) { - if laddr.Port == 0 && isBrokenOpenSSHVersion(string(c.ServerVersion())) { - return c.autoPortListenWorkaround(laddr) - } - - m := channelForwardMsg{ - laddr.IP.String(), - uint32(laddr.Port), - } - // send message - ok, resp, err := c.SendRequest("tcpip-forward", true, Marshal(&m)) - if err != nil { - return nil, err - } - if !ok { - return nil, errors.New("ssh: tcpip-forward request denied by peer") - } - - // If the original port was 0, then the remote side will - // supply a real port number in the response. - if laddr.Port == 0 { - var p struct { - Port uint32 - } - if err := Unmarshal(resp, &p); err != nil { - return nil, err - } - laddr.Port = int(p.Port) - } - - // Register this forward, using the port number we obtained. - ch := c.forwards.add(*laddr) - - return &tcpListener{laddr, c, ch}, nil -} - -// forwardList stores a mapping between remote -// forward requests and the tcpListeners. -type forwardList struct { - sync.Mutex - entries []forwardEntry -} - -// forwardEntry represents an established mapping of a laddr on a -// remote ssh server to a channel connected to a tcpListener. -type forwardEntry struct { - laddr net.TCPAddr - c chan forward -} - -// forward represents an incoming forwarded tcpip connection. The -// arguments to add/remove/lookup should be address as specified in -// the original forward-request. -type forward struct { - newCh NewChannel // the ssh client channel underlying this forward - raddr *net.TCPAddr // the raddr of the incoming connection -} - -func (l *forwardList) add(addr net.TCPAddr) chan forward { - l.Lock() - defer l.Unlock() - f := forwardEntry{ - addr, - make(chan forward, 1), - } - l.entries = append(l.entries, f) - return f.c -} - -// See RFC 4254, section 7.2 -type forwardedTCPPayload struct { - Addr string - Port uint32 - OriginAddr string - OriginPort uint32 -} - -// parseTCPAddr parses the originating address from the remote into a *net.TCPAddr. -func parseTCPAddr(addr string, port uint32) (*net.TCPAddr, error) { - if port == 0 || port > 65535 { - return nil, fmt.Errorf("ssh: port number out of range: %d", port) - } - ip := net.ParseIP(string(addr)) - if ip == nil { - return nil, fmt.Errorf("ssh: cannot parse IP address %q", addr) - } - return &net.TCPAddr{IP: ip, Port: int(port)}, nil -} - -func (l *forwardList) handleChannels(in <-chan NewChannel) { - for ch := range in { - var payload forwardedTCPPayload - if err := Unmarshal(ch.ExtraData(), &payload); err != nil { - ch.Reject(ConnectionFailed, "could not parse forwarded-tcpip payload: "+err.Error()) - continue - } - - // RFC 4254 section 7.2 specifies that incoming - // addresses should list the address, in string - // format. It is implied that this should be an IP - // address, as it would be impossible to connect to it - // otherwise. - laddr, err := parseTCPAddr(payload.Addr, payload.Port) - if err != nil { - ch.Reject(ConnectionFailed, err.Error()) - continue - } - raddr, err := parseTCPAddr(payload.OriginAddr, payload.OriginPort) - if err != nil { - ch.Reject(ConnectionFailed, err.Error()) - continue - } - - if ok := l.forward(*laddr, *raddr, ch); !ok { - // Section 7.2, implementations MUST reject spurious incoming - // connections. - ch.Reject(Prohibited, "no forward for address") - continue - } - } -} - -// remove removes the forward entry, and the channel feeding its -// listener. -func (l *forwardList) remove(addr net.TCPAddr) { - l.Lock() - defer l.Unlock() - for i, f := range l.entries { - if addr.IP.Equal(f.laddr.IP) && addr.Port == f.laddr.Port { - l.entries = append(l.entries[:i], l.entries[i+1:]...) - close(f.c) - return - } - } -} - -// closeAll closes and clears all forwards. -func (l *forwardList) closeAll() { - l.Lock() - defer l.Unlock() - for _, f := range l.entries { - close(f.c) - } - l.entries = nil -} - -func (l *forwardList) forward(laddr, raddr net.TCPAddr, ch NewChannel) bool { - l.Lock() - defer l.Unlock() - for _, f := range l.entries { - if laddr.IP.Equal(f.laddr.IP) && laddr.Port == f.laddr.Port { - f.c <- forward{ch, &raddr} - return true - } - } - return false -} - -type tcpListener struct { - laddr *net.TCPAddr - - conn *Client - in <-chan forward -} - -// Accept waits for and returns the next connection to the listener. -func (l *tcpListener) Accept() (net.Conn, error) { - s, ok := <-l.in - if !ok { - return nil, io.EOF - } - ch, incoming, err := s.newCh.Accept() - if err != nil { - return nil, err - } - go DiscardRequests(incoming) - - return &tcpChanConn{ - Channel: ch, - laddr: l.laddr, - raddr: s.raddr, - }, nil -} - -// Close closes the listener. -func (l *tcpListener) Close() error { - m := channelForwardMsg{ - l.laddr.IP.String(), - uint32(l.laddr.Port), - } - - // this also closes the listener. - l.conn.forwards.remove(*l.laddr) - ok, _, err := l.conn.SendRequest("cancel-tcpip-forward", true, Marshal(&m)) - if err == nil && !ok { - err = errors.New("ssh: cancel-tcpip-forward failed") - } - return err -} - -// Addr returns the listener's network address. -func (l *tcpListener) Addr() net.Addr { - return l.laddr -} - -// Dial initiates a connection to the addr from the remote host. -// The resulting connection has a zero LocalAddr() and RemoteAddr(). -func (c *Client) Dial(n, addr string) (net.Conn, error) { - // Parse the address into host and numeric port. - host, portString, err := net.SplitHostPort(addr) - if err != nil { - return nil, err - } - port, err := strconv.ParseUint(portString, 10, 16) - if err != nil { - return nil, err - } - // Use a zero address for local and remote address. - zeroAddr := &net.TCPAddr{ - IP: net.IPv4zero, - Port: 0, - } - ch, err := c.dial(net.IPv4zero.String(), 0, host, int(port)) - if err != nil { - return nil, err - } - return &tcpChanConn{ - Channel: ch, - laddr: zeroAddr, - raddr: zeroAddr, - }, nil -} - -// DialTCP connects to the remote address raddr on the network net, -// which must be "tcp", "tcp4", or "tcp6". If laddr is not nil, it is used -// as the local address for the connection. -func (c *Client) DialTCP(n string, laddr, raddr *net.TCPAddr) (net.Conn, error) { - if laddr == nil { - laddr = &net.TCPAddr{ - IP: net.IPv4zero, - Port: 0, - } - } - ch, err := c.dial(laddr.IP.String(), laddr.Port, raddr.IP.String(), raddr.Port) - if err != nil { - return nil, err - } - return &tcpChanConn{ - Channel: ch, - laddr: laddr, - raddr: raddr, - }, nil -} - -// RFC 4254 7.2 -type channelOpenDirectMsg struct { - raddr string - rport uint32 - laddr string - lport uint32 -} - -func (c *Client) dial(laddr string, lport int, raddr string, rport int) (Channel, error) { - msg := channelOpenDirectMsg{ - raddr: raddr, - rport: uint32(rport), - laddr: laddr, - lport: uint32(lport), - } - ch, in, err := c.OpenChannel("direct-tcpip", Marshal(&msg)) - if err != nil { - return nil, err - } - go DiscardRequests(in) - return ch, err -} - -type tcpChan struct { - Channel // the backing channel -} - -// tcpChanConn fulfills the net.Conn interface without -// the tcpChan having to hold laddr or raddr directly. -type tcpChanConn struct { - Channel - laddr, raddr net.Addr -} - -// LocalAddr returns the local network address. -func (t *tcpChanConn) LocalAddr() net.Addr { - return t.laddr -} - -// RemoteAddr returns the remote network address. -func (t *tcpChanConn) RemoteAddr() net.Addr { - return t.raddr -} - -// SetDeadline sets the read and write deadlines associated -// with the connection. -func (t *tcpChanConn) SetDeadline(deadline time.Time) error { - if err := t.SetReadDeadline(deadline); err != nil { - return err - } - return t.SetWriteDeadline(deadline) -} - -// SetReadDeadline sets the read deadline. -// A zero value for t means Read will not time out. -// After the deadline, the error from Read will implement net.Error -// with Timeout() == true. -func (t *tcpChanConn) SetReadDeadline(deadline time.Time) error { - return errors.New("ssh: tcpChan: deadline not supported") -} - -// SetWriteDeadline exists to satisfy the net.Conn interface -// but is not implemented by this type. It always returns an error. -func (t *tcpChanConn) SetWriteDeadline(deadline time.Time) error { - return errors.New("ssh: tcpChan: deadline not supported") -} diff --git a/vendor/golang.org/x/crypto/ssh/transport.go b/vendor/golang.org/x/crypto/ssh/transport.go deleted file mode 100644 index 62fba62..0000000 --- a/vendor/golang.org/x/crypto/ssh/transport.go +++ /dev/null @@ -1,333 +0,0 @@ -// Copyright 2011 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 ssh - -import ( - "bufio" - "errors" - "io" -) - -const ( - gcmCipherID = "aes128-gcm@openssh.com" - aes128cbcID = "aes128-cbc" - tripledescbcID = "3des-cbc" -) - -// packetConn represents a transport that implements packet based -// operations. -type packetConn interface { - // Encrypt and send a packet of data to the remote peer. - writePacket(packet []byte) error - - // Read a packet from the connection - readPacket() ([]byte, error) - - // Close closes the write-side of the connection. - Close() error -} - -// transport is the keyingTransport that implements the SSH packet -// protocol. -type transport struct { - reader connectionState - writer connectionState - - bufReader *bufio.Reader - bufWriter *bufio.Writer - rand io.Reader - - io.Closer -} - -// packetCipher represents a combination of SSH encryption/MAC -// protocol. A single instance should be used for one direction only. -type packetCipher interface { - // writePacket encrypts the packet and writes it to w. The - // contents of the packet are generally scrambled. - writePacket(seqnum uint32, w io.Writer, rand io.Reader, packet []byte) error - - // readPacket reads and decrypts a packet of data. The - // returned packet may be overwritten by future calls of - // readPacket. - readPacket(seqnum uint32, r io.Reader) ([]byte, error) -} - -// connectionState represents one side (read or write) of the -// connection. This is necessary because each direction has its own -// keys, and can even have its own algorithms -type connectionState struct { - packetCipher - seqNum uint32 - dir direction - pendingKeyChange chan packetCipher -} - -// prepareKeyChange sets up key material for a keychange. The key changes in -// both directions are triggered by reading and writing a msgNewKey packet -// respectively. -func (t *transport) prepareKeyChange(algs *algorithms, kexResult *kexResult) error { - if ciph, err := newPacketCipher(t.reader.dir, algs.r, kexResult); err != nil { - return err - } else { - t.reader.pendingKeyChange <- ciph - } - - if ciph, err := newPacketCipher(t.writer.dir, algs.w, kexResult); err != nil { - return err - } else { - t.writer.pendingKeyChange <- ciph - } - - return nil -} - -// Read and decrypt next packet. -func (t *transport) readPacket() ([]byte, error) { - return t.reader.readPacket(t.bufReader) -} - -func (s *connectionState) readPacket(r *bufio.Reader) ([]byte, error) { - packet, err := s.packetCipher.readPacket(s.seqNum, r) - s.seqNum++ - if err == nil && len(packet) == 0 { - err = errors.New("ssh: zero length packet") - } - - if len(packet) > 0 { - switch packet[0] { - case msgNewKeys: - select { - case cipher := <-s.pendingKeyChange: - s.packetCipher = cipher - default: - return nil, errors.New("ssh: got bogus newkeys message.") - } - - case msgDisconnect: - // Transform a disconnect message into an - // error. Since this is lowest level at which - // we interpret message types, doing it here - // ensures that we don't have to handle it - // elsewhere. - var msg disconnectMsg - if err := Unmarshal(packet, &msg); err != nil { - return nil, err - } - return nil, &msg - } - } - - // The packet may point to an internal buffer, so copy the - // packet out here. - fresh := make([]byte, len(packet)) - copy(fresh, packet) - - return fresh, err -} - -func (t *transport) writePacket(packet []byte) error { - return t.writer.writePacket(t.bufWriter, t.rand, packet) -} - -func (s *connectionState) writePacket(w *bufio.Writer, rand io.Reader, packet []byte) error { - changeKeys := len(packet) > 0 && packet[0] == msgNewKeys - - err := s.packetCipher.writePacket(s.seqNum, w, rand, packet) - if err != nil { - return err - } - if err = w.Flush(); err != nil { - return err - } - s.seqNum++ - if changeKeys { - select { - case cipher := <-s.pendingKeyChange: - s.packetCipher = cipher - default: - panic("ssh: no key material for msgNewKeys") - } - } - return err -} - -func newTransport(rwc io.ReadWriteCloser, rand io.Reader, isClient bool) *transport { - t := &transport{ - bufReader: bufio.NewReader(rwc), - bufWriter: bufio.NewWriter(rwc), - rand: rand, - reader: connectionState{ - packetCipher: &streamPacketCipher{cipher: noneCipher{}}, - pendingKeyChange: make(chan packetCipher, 1), - }, - writer: connectionState{ - packetCipher: &streamPacketCipher{cipher: noneCipher{}}, - pendingKeyChange: make(chan packetCipher, 1), - }, - Closer: rwc, - } - if isClient { - t.reader.dir = serverKeys - t.writer.dir = clientKeys - } else { - t.reader.dir = clientKeys - t.writer.dir = serverKeys - } - - return t -} - -type direction struct { - ivTag []byte - keyTag []byte - macKeyTag []byte -} - -var ( - serverKeys = direction{[]byte{'B'}, []byte{'D'}, []byte{'F'}} - clientKeys = direction{[]byte{'A'}, []byte{'C'}, []byte{'E'}} -) - -// generateKeys generates key material for IV, MAC and encryption. -func generateKeys(d direction, algs directionAlgorithms, kex *kexResult) (iv, key, macKey []byte) { - cipherMode := cipherModes[algs.Cipher] - macMode := macModes[algs.MAC] - - iv = make([]byte, cipherMode.ivSize) - key = make([]byte, cipherMode.keySize) - macKey = make([]byte, macMode.keySize) - - generateKeyMaterial(iv, d.ivTag, kex) - generateKeyMaterial(key, d.keyTag, kex) - generateKeyMaterial(macKey, d.macKeyTag, kex) - return -} - -// setupKeys sets the cipher and MAC keys from kex.K, kex.H and sessionId, as -// described in RFC 4253, section 6.4. direction should either be serverKeys -// (to setup server->client keys) or clientKeys (for client->server keys). -func newPacketCipher(d direction, algs directionAlgorithms, kex *kexResult) (packetCipher, error) { - iv, key, macKey := generateKeys(d, algs, kex) - - if algs.Cipher == gcmCipherID { - return newGCMCipher(iv, key, macKey) - } - - if algs.Cipher == aes128cbcID { - return newAESCBCCipher(iv, key, macKey, algs) - } - - if algs.Cipher == tripledescbcID { - return newTripleDESCBCCipher(iv, key, macKey, algs) - } - - c := &streamPacketCipher{ - mac: macModes[algs.MAC].new(macKey), - } - c.macResult = make([]byte, c.mac.Size()) - - var err error - c.cipher, err = cipherModes[algs.Cipher].createStream(key, iv) - if err != nil { - return nil, err - } - - return c, nil -} - -// generateKeyMaterial fills out with key material generated from tag, K, H -// and sessionId, as specified in RFC 4253, section 7.2. -func generateKeyMaterial(out, tag []byte, r *kexResult) { - var digestsSoFar []byte - - h := r.Hash.New() - for len(out) > 0 { - h.Reset() - h.Write(r.K) - h.Write(r.H) - - if len(digestsSoFar) == 0 { - h.Write(tag) - h.Write(r.SessionID) - } else { - h.Write(digestsSoFar) - } - - digest := h.Sum(nil) - n := copy(out, digest) - out = out[n:] - if len(out) > 0 { - digestsSoFar = append(digestsSoFar, digest...) - } - } -} - -const packageVersion = "SSH-2.0-Go" - -// Sends and receives a version line. The versionLine string should -// be US ASCII, start with "SSH-2.0-", and should not include a -// newline. exchangeVersions returns the other side's version line. -func exchangeVersions(rw io.ReadWriter, versionLine []byte) (them []byte, err error) { - // Contrary to the RFC, we do not ignore lines that don't - // start with "SSH-2.0-" to make the library usable with - // nonconforming servers. - for _, c := range versionLine { - // The spec disallows non US-ASCII chars, and - // specifically forbids null chars. - if c < 32 { - return nil, errors.New("ssh: junk character in version line") - } - } - if _, err = rw.Write(append(versionLine, '\r', '\n')); err != nil { - return - } - - them, err = readVersion(rw) - return them, err -} - -// maxVersionStringBytes is the maximum number of bytes that we'll -// accept as a version string. RFC 4253 section 4.2 limits this at 255 -// chars -const maxVersionStringBytes = 255 - -// Read version string as specified by RFC 4253, section 4.2. -func readVersion(r io.Reader) ([]byte, error) { - versionString := make([]byte, 0, 64) - var ok bool - var buf [1]byte - - for len(versionString) < maxVersionStringBytes { - _, err := io.ReadFull(r, buf[:]) - if err != nil { - return nil, err - } - // The RFC says that the version should be terminated with \r\n - // but several SSH servers actually only send a \n. - if buf[0] == '\n' { - ok = true - break - } - - // non ASCII chars are disallowed, but we are lenient, - // since Go doesn't use null-terminated strings. - - // The RFC allows a comment after a space, however, - // all of it (version and comments) goes into the - // session hash. - versionString = append(versionString, buf[0]) - } - - if !ok { - return nil, errors.New("ssh: overflow reading version string") - } - - // There might be a '\r' on the end which we should remove. - if len(versionString) > 0 && versionString[len(versionString)-1] == '\r' { - versionString = versionString[:len(versionString)-1] - } - return versionString, nil -} diff --git a/vendor/golang.org/x/sys/unix/asm_linux_mipsx.s b/vendor/golang.org/x/sys/unix/asm_linux_mipsx.s new file mode 100644 index 0000000..2ea4257 --- /dev/null +++ b/vendor/golang.org/x/sys/unix/asm_linux_mipsx.s @@ -0,0 +1,31 @@ +// Copyright 2016 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 +// +build mips mipsle +// +build !gccgo + +#include "textflag.h" + +// +// System calls for mips, Linux +// + +// Just jump to package syscall's implementation for all these functions. +// The runtime may know about them. + +TEXT ·Syscall(SB),NOSPLIT,$0-28 + JMP syscall·Syscall(SB) + +TEXT ·Syscall6(SB),NOSPLIT,$0-40 + JMP syscall·Syscall6(SB) + +TEXT ·Syscall9(SB),NOSPLIT,$0-52 + JMP syscall·Syscall9(SB) + +TEXT ·RawSyscall(SB),NOSPLIT,$0-28 + JMP syscall·RawSyscall(SB) + +TEXT ·RawSyscall6(SB),NOSPLIT,$0-40 + JMP syscall·RawSyscall6(SB) diff --git a/vendor/golang.org/x/sys/unix/flock_linux_32bit.go b/vendor/golang.org/x/sys/unix/flock_linux_32bit.go index 362831c..fc0e50e 100644 --- a/vendor/golang.org/x/sys/unix/flock_linux_32bit.go +++ b/vendor/golang.org/x/sys/unix/flock_linux_32bit.go @@ -1,4 +1,4 @@ -// +build linux,386 linux,arm +// +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 diff --git a/vendor/golang.org/x/sys/unix/mkerrors.sh b/vendor/golang.org/x/sys/unix/mkerrors.sh index 33b7922..7e6276b 100755 --- a/vendor/golang.org/x/sys/unix/mkerrors.sh +++ b/vendor/golang.org/x/sys/unix/mkerrors.sh @@ -128,6 +128,7 @@ includes_Linux=' #include #include #include +#include #include #include @@ -339,6 +340,7 @@ ccflags="$@" $2 !~ /^(BPF_TIMEVAL)$/ && $2 ~ /^(BPF|DLT)_/ || $2 ~ /^CLOCK_/ || + $2 ~ /^CAN_/ || $2 !~ "WMESGLEN" && $2 ~ /^W[A-Z0-9]+$/ {printf("\t%s = C.%s\n", $2, $2)} $2 ~ /^__WCOREFLAG$/ {next} diff --git a/vendor/golang.org/x/sys/unix/mksysnum_linux.pl b/vendor/golang.org/x/sys/unix/mksysnum_linux.pl index 4d4017d..52b1613 100755 --- a/vendor/golang.org/x/sys/unix/mksysnum_linux.pl +++ b/vendor/golang.org/x/sys/unix/mksysnum_linux.pl @@ -23,6 +23,8 @@ package unix const( EOF +my $offset = 0; + sub fmt { my ($name, $num) = @_; if($num > 999){ @@ -31,13 +33,18 @@ sub fmt { return; } $name =~ y/a-z/A-Z/; + $num = $num + $offset; print " SYS_$name = $num;\n"; } my $prev; open(GCC, "gcc -E -dD $ARGV[0] |") || die "can't run gcc"; while(){ - if(/^#define __NR_syscalls\s+/) { + if(/^#define __NR_Linux\s+([0-9]+)/){ + # mips/mips64: extract offset + $offset = $1; + } + elsif(/^#define __NR_syscalls\s+/) { # ignore redefinitions of __NR_syscalls } elsif(/^#define __NR_(\w+)\s+([0-9]+)/){ @@ -51,6 +58,9 @@ sub fmt { elsif(/^#define __NR_(\w+)\s+\(\w+\+\s*([0-9]+)\)/){ fmt($1, $prev+$2) } + elsif(/^#define __NR_(\w+)\s+\(__NR_Linux \+ ([0-9]+)/){ + fmt($1, $2); + } } print < 0 && buf[n-1] == '\x00' { diff --git a/vendor/golang.org/x/sys/unix/syscall_linux.go b/vendor/golang.org/x/sys/unix/syscall_linux.go index cfac4a4..01c569a 100644 --- a/vendor/golang.org/x/sys/unix/syscall_linux.go +++ b/vendor/golang.org/x/sys/unix/syscall_linux.go @@ -411,6 +411,47 @@ func (sa *SockaddrHCI) sockaddr() (unsafe.Pointer, _Socklen, error) { return unsafe.Pointer(&sa.raw), SizeofSockaddrHCI, nil } +// SockaddrCAN implements the Sockaddr interface for AF_CAN type sockets. +// The RxID and TxID fields are used for transport protocol addressing in +// (CAN_TP16, CAN_TP20, CAN_MCNET, and CAN_ISOTP), they can be left with +// zero values for CAN_RAW and CAN_BCM sockets as they have no meaning. +// +// The SockaddrCAN struct must be bound to the socket file descriptor +// using Bind before the CAN socket can be used. +// +// // Read one raw CAN frame +// fd, _ := Socket(AF_CAN, SOCK_RAW, CAN_RAW) +// addr := &SockaddrCAN{Ifindex: index} +// Bind(fd, addr) +// frame := make([]byte, 16) +// Read(fd, frame) +// +// The full SocketCAN documentation can be found in the linux kernel +// archives at: https://www.kernel.org/doc/Documentation/networking/can.txt +type SockaddrCAN struct { + Ifindex int + RxID uint32 + TxID uint32 + raw RawSockaddrCAN +} + +func (sa *SockaddrCAN) sockaddr() (unsafe.Pointer, _Socklen, error) { + if sa.Ifindex < 0 || sa.Ifindex > 0x7fffffff { + return nil, 0, EINVAL + } + sa.raw.Family = AF_CAN + sa.raw.Ifindex = int32(sa.Ifindex) + rx := (*[4]byte)(unsafe.Pointer(&sa.RxID)) + for i := 0; i < 4; i++ { + sa.raw.Addr[i] = rx[i] + } + tx := (*[4]byte)(unsafe.Pointer(&sa.TxID)) + for i := 0; i < 4; i++ { + sa.raw.Addr[i+4] = tx[i] + } + return unsafe.Pointer(&sa.raw), SizeofSockaddrCAN, nil +} + func anyToSockaddr(rsa *RawSockaddrAny) (Sockaddr, error) { switch rsa.Addr.Family { case AF_NETLINK: @@ -899,6 +940,7 @@ func Getpgrp() (pid int) { //sysnb Getppid() (ppid int) //sys Getpriority(which int, who int) (prio int, err error) //sysnb Getrusage(who int, rusage *Rusage) (err error) +//sysnb Getsid(pid int) (sid int, err error) //sysnb Gettid() (tid int) //sys Getxattr(path string, attr string, dest []byte) (sz int, err error) //sys InotifyAddWatch(fd int, pathname string, mask uint32) (watchdesc int, err error) @@ -911,7 +953,7 @@ func Getpgrp() (pid int) { //sys Mknodat(dirfd int, path string, mode uint32, dev int) (err error) //sys Nanosleep(time *Timespec, leftover *Timespec) (err error) //sys PivotRoot(newroot string, putold string) (err error) = SYS_PIVOT_ROOT -//sysnb prlimit(pid int, resource int, old *Rlimit, newlimit *Rlimit) (err error) = SYS_PRLIMIT64 +//sysnb prlimit(pid int, resource int, newlimit *Rlimit, old *Rlimit) (err error) = SYS_PRLIMIT64 //sys Prctl(option int, arg2 uintptr, arg3 uintptr, arg4 uintptr, arg5 uintptr) (err error) //sys read(fd int, p []byte) (n int, err error) //sys Removexattr(path string, attr string) (err error) diff --git a/vendor/golang.org/x/sys/unix/syscall_linux_amd64.go b/vendor/golang.org/x/sys/unix/syscall_linux_amd64.go index 18911c2..9516a3f 100644 --- a/vendor/golang.org/x/sys/unix/syscall_linux_amd64.go +++ b/vendor/golang.org/x/sys/unix/syscall_linux_amd64.go @@ -6,8 +6,6 @@ package unix -import "syscall" - //sys Dup2(oldfd int, newfd int) (err error) //sys EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) //sys Fadvise(fd int, offset int64, length int64, advice int) (err error) = SYS_FADVISE64 @@ -63,9 +61,6 @@ import "syscall" //sys sendmsg(s int, msg *Msghdr, flags int) (n int, err error) //sys mmap(addr uintptr, length uintptr, prot int, flags int, fd int, offset int64) (xaddr uintptr, err error) -//go:noescape -func gettimeofday(tv *Timeval) (err syscall.Errno) - func Gettimeofday(tv *Timeval) (err error) { errno := gettimeofday(tv) if errno != 0 { diff --git a/vendor/golang.org/x/sys/unix/syscall_linux_amd64_gc.go b/vendor/golang.org/x/sys/unix/syscall_linux_amd64_gc.go new file mode 100644 index 0000000..21a4946 --- /dev/null +++ b/vendor/golang.org/x/sys/unix/syscall_linux_amd64_gc.go @@ -0,0 +1,13 @@ +// Copyright 2016 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 amd64,linux +// +build !gccgo + +package unix + +import "syscall" + +//go:noescape +func gettimeofday(tv *Timeval) (err syscall.Errno) diff --git a/vendor/golang.org/x/sys/unix/syscall_linux_mipsx.go b/vendor/golang.org/x/sys/unix/syscall_linux_mipsx.go new file mode 100644 index 0000000..5ed8013 --- /dev/null +++ b/vendor/golang.org/x/sys/unix/syscall_linux_mipsx.go @@ -0,0 +1,241 @@ +// Copyright 2016 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 +// +build mips mipsle + +package unix + +import ( + "syscall" + "unsafe" +) + +func Syscall9(trap, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err syscall.Errno) + +//sys Dup2(oldfd int, newfd int) (err error) +//sys Fchown(fd int, uid int, gid int) (err error) +//sys Ftruncate(fd int, length int64) (err error) = SYS_FTRUNCATE64 +//sysnb Getegid() (egid int) +//sysnb Geteuid() (euid int) +//sysnb Getgid() (gid int) +//sysnb Getuid() (uid int) +//sys Lchown(path string, uid int, gid int) (err error) +//sys Listen(s int, n int) (err error) +//sys Pread(fd int, p []byte, offset int64) (n int, err error) = SYS_PREAD64 +//sys Pwrite(fd int, p []byte, offset int64) (n int, err error) = SYS_PWRITE64 +//sys Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) = SYS__NEWSELECT +//sys sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) = SYS_SENDFILE64 +//sys Setfsgid(gid int) (err error) +//sys Setfsuid(uid int) (err error) +//sysnb Setregid(rgid int, egid int) (err error) +//sysnb Setresgid(rgid int, egid int, sgid int) (err error) +//sysnb Setresuid(ruid int, euid int, suid int) (err error) + +//sysnb Setreuid(ruid int, euid int) (err error) +//sys Shutdown(fd int, how int) (err error) +//sys Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int64, err error) + +//sys SyncFileRange(fd int, off int64, n int64, flags int) (err error) +//sys Truncate(path string, length int64) (err error) = SYS_TRUNCATE64 +//sys accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) +//sys accept4(s int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (fd int, err error) +//sys bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) +//sys connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) +//sysnb getgroups(n int, list *_Gid_t) (nn int, err error) +//sysnb setgroups(n int, list *_Gid_t) (err error) +//sys getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) +//sys setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) +//sysnb socket(domain int, typ int, proto int) (fd int, err error) +//sysnb socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) +//sysnb getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) +//sysnb getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) +//sys recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) +//sys sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) +//sys recvmsg(s int, msg *Msghdr, flags int) (n int, err error) +//sys sendmsg(s int, msg *Msghdr, flags int) (n int, err error) + +//sysnb InotifyInit() (fd int, err error) +//sys Ioperm(from int, num int, on int) (err error) +//sys Iopl(level int) (err error) + +//sysnb Gettimeofday(tv *Timeval) (err error) +//sysnb Time(t *Time_t) (tt Time_t, err error) + +//sys Lstat(path string, stat *Stat_t) (err error) = SYS_LSTAT64 +//sys Fstat(fd int, stat *Stat_t) (err error) = SYS_FSTAT64 +//sys Stat(path string, stat *Stat_t) (err error) = SYS_STAT64 + +//sys Utime(path string, buf *Utimbuf) (err error) +//sys EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) +//sys Pause() (err error) + +func Fstatfs(fd int, buf *Statfs_t) (err error) { + _, _, e := Syscall(SYS_FSTATFS64, uintptr(fd), unsafe.Sizeof(*buf), uintptr(unsafe.Pointer(buf))) + use(unsafe.Pointer(buf)) + if e != 0 { + err = errnoErr(e) + } + return +} + +func Statfs(path string, buf *Statfs_t) (err error) { + p, err := BytePtrFromString(path) + if err != nil { + return err + } + _, _, e := Syscall(SYS_STATFS64, uintptr(unsafe.Pointer(p)), unsafe.Sizeof(*buf), uintptr(unsafe.Pointer(buf))) + use(unsafe.Pointer(p)) + if e != 0 { + err = errnoErr(e) + } + return +} + +func Seek(fd int, offset int64, whence int) (off int64, err error) { + _, _, e := Syscall6(SYS__LLSEEK, uintptr(fd), uintptr(offset>>32), uintptr(offset), uintptr(unsafe.Pointer(&off)), uintptr(whence), 0) + if e != 0 { + err = errnoErr(e) + } + return +} + +func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) } + +func NsecToTimespec(nsec int64) (ts Timespec) { + ts.Sec = int32(nsec / 1e9) + ts.Nsec = int32(nsec % 1e9) + return +} + +func NsecToTimeval(nsec int64) (tv Timeval) { + nsec += 999 // round up to microsecond + tv.Sec = int32(nsec / 1e9) + tv.Usec = int32(nsec % 1e9 / 1e3) + return +} + +//sysnb pipe2(p *[2]_C_int, flags int) (err error) + +func Pipe2(p []int, flags int) (err error) { + if len(p) != 2 { + return EINVAL + } + var pp [2]_C_int + err = pipe2(&pp, flags) + p[0] = int(pp[0]) + p[1] = int(pp[1]) + return +} + +func Pipe(p []int) (err error) { + if len(p) != 2 { + return EINVAL + } + var pp [2]_C_int + err = pipe2(&pp, 0) + p[0] = int(pp[0]) + p[1] = int(pp[1]) + return +} + +//sys mmap2(addr uintptr, length uintptr, prot int, flags int, fd int, pageOffset uintptr) (xaddr uintptr, err error) + +func mmap(addr uintptr, length uintptr, prot int, flags int, fd int, offset int64) (xaddr uintptr, err error) { + page := uintptr(offset / 4096) + if offset != int64(page)*4096 { + return 0, EINVAL + } + return mmap2(addr, length, prot, flags, fd, page) +} + +const rlimInf32 = ^uint32(0) +const rlimInf64 = ^uint64(0) + +type rlimit32 struct { + Cur uint32 + Max uint32 +} + +//sysnb getrlimit(resource int, rlim *rlimit32) (err error) = SYS_GETRLIMIT + +func Getrlimit(resource int, rlim *Rlimit) (err error) { + err = prlimit(0, resource, nil, rlim) + if err != ENOSYS { + return err + } + + rl := rlimit32{} + err = getrlimit(resource, &rl) + if err != nil { + return + } + + if rl.Cur == rlimInf32 { + rlim.Cur = rlimInf64 + } else { + rlim.Cur = uint64(rl.Cur) + } + + if rl.Max == rlimInf32 { + rlim.Max = rlimInf64 + } else { + rlim.Max = uint64(rl.Max) + } + return +} + +//sysnb setrlimit(resource int, rlim *rlimit32) (err error) = SYS_SETRLIMIT + +func Setrlimit(resource int, rlim *Rlimit) (err error) { + err = prlimit(0, resource, rlim, nil) + if err != ENOSYS { + return err + } + + rl := rlimit32{} + if rlim.Cur == rlimInf64 { + rl.Cur = rlimInf32 + } else if rlim.Cur < uint64(rlimInf32) { + rl.Cur = uint32(rlim.Cur) + } else { + return EINVAL + } + if rlim.Max == rlimInf64 { + rl.Max = rlimInf32 + } else if rlim.Max < uint64(rlimInf32) { + rl.Max = uint32(rlim.Max) + } else { + return EINVAL + } + + return setrlimit(resource, &rl) +} + +func (r *PtraceRegs) PC() uint64 { return uint64(r.Regs[64]) } + +func (r *PtraceRegs) SetPC(pc uint64) { r.Regs[64] = uint32(pc) } + +func (iov *Iovec) SetLen(length int) { + iov.Len = uint32(length) +} + +func (msghdr *Msghdr) SetControllen(length int) { + msghdr.Controllen = uint32(length) +} + +func (cmsg *Cmsghdr) SetLen(length int) { + cmsg.Len = uint32(length) +} + +//sys poll(fds *PollFd, nfds int, timeout int) (n int, err error) + +func Poll(fds []PollFd, timeout int) (n int, err error) { + if len(fds) == 0 { + return poll(nil, 0, timeout) + } + return poll(&fds[0], len(fds), timeout) +} + +func Getpagesize() int { return 4096 } diff --git a/vendor/golang.org/x/sys/unix/syscall_unix.go b/vendor/golang.org/x/sys/unix/syscall_unix.go index b46b250..8a5237d 100644 --- a/vendor/golang.org/x/sys/unix/syscall_unix.go +++ b/vendor/golang.org/x/sys/unix/syscall_unix.go @@ -49,11 +49,6 @@ func errnoErr(e syscall.Errno) error { return e } -func Syscall(trap, a1, a2, a3 uintptr) (r1, r2 uintptr, err syscall.Errno) -func Syscall6(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err syscall.Errno) -func RawSyscall(trap, a1, a2, a3 uintptr) (r1, r2 uintptr, err syscall.Errno) -func RawSyscall6(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err syscall.Errno) - // Mmap manager, for use by operating system-specific implementations. type mmapper struct { diff --git a/vendor/golang.org/x/sys/unix/syscall_unix_gc.go b/vendor/golang.org/x/sys/unix/syscall_unix_gc.go new file mode 100644 index 0000000..4cb8e8e --- /dev/null +++ b/vendor/golang.org/x/sys/unix/syscall_unix_gc.go @@ -0,0 +1,15 @@ +// Copyright 2016 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 dragonfly freebsd linux netbsd openbsd solaris +// +build !gccgo + +package unix + +import "syscall" + +func Syscall(trap, a1, a2, a3 uintptr) (r1, r2 uintptr, err syscall.Errno) +func Syscall6(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err syscall.Errno) +func RawSyscall(trap, a1, a2, a3 uintptr) (r1, r2 uintptr, err syscall.Errno) +func RawSyscall6(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err syscall.Errno) diff --git a/vendor/golang.org/x/sys/unix/types_linux.go b/vendor/golang.org/x/sys/unix/types_linux.go index de80e2c..f3d8f90 100644 --- a/vendor/golang.org/x/sys/unix/types_linux.go +++ b/vendor/golang.org/x/sys/unix/types_linux.go @@ -58,6 +58,7 @@ package unix #include #include #include +#include #ifdef TCSETS2 // On systems that have "struct termios2" use this as type Termios. @@ -125,7 +126,7 @@ typedef struct {} ptracePer; // The real epoll_event is a union, and godefs doesn't handle it well. struct my_epoll_event { uint32_t events; -#if defined(__ARM_EABI__) || defined(__aarch64__) +#if defined(__ARM_EABI__) || defined(__aarch64__) || (defined(__mips__) && _MIPS_SIM == _ABIO32) // padding is not specified in linux/eventpoll.h but added to conform to the // alignment requirements of EABI int32_t padFd; @@ -218,6 +219,8 @@ type RawSockaddrNetlink C.struct_sockaddr_nl type RawSockaddrHCI C.struct_sockaddr_hci +type RawSockaddrCAN C.struct_sockaddr_can + type RawSockaddr C.struct_sockaddr type RawSockaddrAny C.struct_sockaddr_any @@ -258,6 +261,7 @@ const ( SizeofSockaddrLinklayer = C.sizeof_struct_sockaddr_ll SizeofSockaddrNetlink = C.sizeof_struct_sockaddr_nl SizeofSockaddrHCI = C.sizeof_struct_sockaddr_hci + SizeofSockaddrCAN = C.sizeof_struct_sockaddr_can SizeofLinger = C.sizeof_struct_linger SizeofIPMreq = C.sizeof_struct_ip_mreq SizeofIPMreqn = C.sizeof_struct_ip_mreqn diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_386.go b/vendor/golang.org/x/sys/unix/zerrors_linux_386.go index 8f92012..b40d029 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_386.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_386.go @@ -190,6 +190,25 @@ const ( BS0 = 0x0 BS1 = 0x2000 BSDLY = 0x2000 + CAN_BCM = 0x2 + CAN_EFF_FLAG = 0x80000000 + CAN_EFF_ID_BITS = 0x1d + CAN_EFF_MASK = 0x1fffffff + CAN_ERR_FLAG = 0x20000000 + CAN_ERR_MASK = 0x1fffffff + CAN_INV_FILTER = 0x20000000 + CAN_ISOTP = 0x6 + CAN_MAX_DLC = 0x8 + CAN_MAX_DLEN = 0x8 + CAN_MCNET = 0x5 + CAN_MTU = 0x10 + CAN_NPROTO = 0x7 + CAN_RAW = 0x1 + CAN_RTR_FLAG = 0x40000000 + CAN_SFF_ID_BITS = 0xb + CAN_SFF_MASK = 0x7ff + CAN_TP16 = 0x3 + CAN_TP20 = 0x4 CBAUD = 0x100f CBAUDEX = 0x1000 CFLUSH = 0xf diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_amd64.go b/vendor/golang.org/x/sys/unix/zerrors_linux_amd64.go index 49b6c35..9f0600c 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_amd64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_amd64.go @@ -190,6 +190,25 @@ const ( BS0 = 0x0 BS1 = 0x2000 BSDLY = 0x2000 + CAN_BCM = 0x2 + CAN_EFF_FLAG = 0x80000000 + CAN_EFF_ID_BITS = 0x1d + CAN_EFF_MASK = 0x1fffffff + CAN_ERR_FLAG = 0x20000000 + CAN_ERR_MASK = 0x1fffffff + CAN_INV_FILTER = 0x20000000 + CAN_ISOTP = 0x6 + CAN_MAX_DLC = 0x8 + CAN_MAX_DLEN = 0x8 + CAN_MCNET = 0x5 + CAN_MTU = 0x10 + CAN_NPROTO = 0x7 + CAN_RAW = 0x1 + CAN_RTR_FLAG = 0x40000000 + CAN_SFF_ID_BITS = 0xb + CAN_SFF_MASK = 0x7ff + CAN_TP16 = 0x3 + CAN_TP20 = 0x4 CBAUD = 0x100f CBAUDEX = 0x1000 CFLUSH = 0xf diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_arm.go b/vendor/golang.org/x/sys/unix/zerrors_linux_arm.go index f036758..647a796 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_arm.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_arm.go @@ -186,6 +186,25 @@ const ( BS0 = 0x0 BS1 = 0x2000 BSDLY = 0x2000 + CAN_BCM = 0x2 + CAN_EFF_FLAG = 0x80000000 + CAN_EFF_ID_BITS = 0x1d + CAN_EFF_MASK = 0x1fffffff + CAN_ERR_FLAG = 0x20000000 + CAN_ERR_MASK = 0x1fffffff + CAN_INV_FILTER = 0x20000000 + CAN_ISOTP = 0x6 + CAN_MAX_DLC = 0x8 + CAN_MAX_DLEN = 0x8 + CAN_MCNET = 0x5 + CAN_MTU = 0x10 + CAN_NPROTO = 0x7 + CAN_RAW = 0x1 + CAN_RTR_FLAG = 0x40000000 + CAN_SFF_ID_BITS = 0xb + CAN_SFF_MASK = 0x7ff + CAN_TP16 = 0x3 + CAN_TP20 = 0x4 CBAUD = 0x100f CBAUDEX = 0x1000 CFLUSH = 0xf diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_arm64.go b/vendor/golang.org/x/sys/unix/zerrors_linux_arm64.go index 16dcbc9..a6d1e1f 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_arm64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_arm64.go @@ -196,6 +196,25 @@ const ( BS0 = 0x0 BS1 = 0x2000 BSDLY = 0x2000 + CAN_BCM = 0x2 + CAN_EFF_FLAG = 0x80000000 + CAN_EFF_ID_BITS = 0x1d + CAN_EFF_MASK = 0x1fffffff + CAN_ERR_FLAG = 0x20000000 + CAN_ERR_MASK = 0x1fffffff + CAN_INV_FILTER = 0x20000000 + CAN_ISOTP = 0x6 + CAN_MAX_DLC = 0x8 + CAN_MAX_DLEN = 0x8 + CAN_MCNET = 0x5 + CAN_MTU = 0x10 + CAN_NPROTO = 0x7 + CAN_RAW = 0x1 + CAN_RTR_FLAG = 0x40000000 + CAN_SFF_ID_BITS = 0xb + CAN_SFF_MASK = 0x7ff + CAN_TP16 = 0x3 + CAN_TP20 = 0x4 CBAUD = 0x100f CBAUDEX = 0x1000 CFLUSH = 0xf diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_mips.go b/vendor/golang.org/x/sys/unix/zerrors_linux_mips.go new file mode 100644 index 0000000..e4fb9ad --- /dev/null +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_mips.go @@ -0,0 +1,1814 @@ +// mkerrors.sh +// MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT + +// +build mips,linux + +// Created by cgo -godefs - DO NOT EDIT +// cgo -godefs -- _const.go + +package unix + +import "syscall" + +const ( + AF_ALG = 0x26 + AF_APPLETALK = 0x5 + AF_ASH = 0x12 + AF_ATMPVC = 0x8 + AF_ATMSVC = 0x14 + AF_AX25 = 0x3 + AF_BLUETOOTH = 0x1f + AF_BRIDGE = 0x7 + AF_CAIF = 0x25 + AF_CAN = 0x1d + AF_DECnet = 0xc + AF_ECONET = 0x13 + AF_FILE = 0x1 + AF_IEEE802154 = 0x24 + AF_INET = 0x2 + AF_INET6 = 0xa + AF_IPX = 0x4 + AF_IRDA = 0x17 + AF_ISDN = 0x22 + AF_IUCV = 0x20 + AF_KEY = 0xf + AF_LLC = 0x1a + AF_LOCAL = 0x1 + AF_MAX = 0x27 + AF_NETBEUI = 0xd + AF_NETLINK = 0x10 + AF_NETROM = 0x6 + AF_PACKET = 0x11 + AF_PHONET = 0x23 + AF_PPPOX = 0x18 + AF_RDS = 0x15 + AF_ROSE = 0xb + AF_ROUTE = 0x10 + AF_RXRPC = 0x21 + AF_SECURITY = 0xe + AF_SNA = 0x16 + AF_TIPC = 0x1e + AF_UNIX = 0x1 + AF_UNSPEC = 0x0 + AF_WANPIPE = 0x19 + AF_X25 = 0x9 + ARPHRD_ADAPT = 0x108 + ARPHRD_APPLETLK = 0x8 + ARPHRD_ARCNET = 0x7 + ARPHRD_ASH = 0x30d + ARPHRD_ATM = 0x13 + ARPHRD_AX25 = 0x3 + ARPHRD_BIF = 0x307 + ARPHRD_CAIF = 0x336 + ARPHRD_CAN = 0x118 + ARPHRD_CHAOS = 0x5 + ARPHRD_CISCO = 0x201 + ARPHRD_CSLIP = 0x101 + ARPHRD_CSLIP6 = 0x103 + ARPHRD_DDCMP = 0x205 + ARPHRD_DLCI = 0xf + ARPHRD_ECONET = 0x30e + ARPHRD_EETHER = 0x2 + ARPHRD_ETHER = 0x1 + ARPHRD_EUI64 = 0x1b + ARPHRD_FCAL = 0x311 + ARPHRD_FCFABRIC = 0x313 + ARPHRD_FCPL = 0x312 + ARPHRD_FCPP = 0x310 + ARPHRD_FDDI = 0x306 + ARPHRD_FRAD = 0x302 + ARPHRD_HDLC = 0x201 + ARPHRD_HIPPI = 0x30c + ARPHRD_HWX25 = 0x110 + ARPHRD_IEEE1394 = 0x18 + ARPHRD_IEEE802 = 0x6 + ARPHRD_IEEE80211 = 0x321 + ARPHRD_IEEE80211_PRISM = 0x322 + ARPHRD_IEEE80211_RADIOTAP = 0x323 + ARPHRD_IEEE802154 = 0x324 + ARPHRD_IEEE802_TR = 0x320 + ARPHRD_INFINIBAND = 0x20 + ARPHRD_IPDDP = 0x309 + ARPHRD_IPGRE = 0x30a + ARPHRD_IRDA = 0x30f + ARPHRD_LAPB = 0x204 + ARPHRD_LOCALTLK = 0x305 + ARPHRD_LOOPBACK = 0x304 + ARPHRD_METRICOM = 0x17 + ARPHRD_NETROM = 0x0 + ARPHRD_NONE = 0xfffe + ARPHRD_PHONET = 0x334 + ARPHRD_PHONET_PIPE = 0x335 + ARPHRD_PIMREG = 0x30b + ARPHRD_PPP = 0x200 + ARPHRD_PRONET = 0x4 + ARPHRD_RAWHDLC = 0x206 + ARPHRD_ROSE = 0x10e + ARPHRD_RSRVD = 0x104 + ARPHRD_SIT = 0x308 + ARPHRD_SKIP = 0x303 + ARPHRD_SLIP = 0x100 + ARPHRD_SLIP6 = 0x102 + ARPHRD_TUNNEL = 0x300 + ARPHRD_TUNNEL6 = 0x301 + ARPHRD_VOID = 0xffff + ARPHRD_X25 = 0x10f + B0 = 0x0 + B1000000 = 0x1008 + B110 = 0x3 + B115200 = 0x1002 + B1152000 = 0x1009 + B1200 = 0x9 + B134 = 0x4 + B150 = 0x5 + B1500000 = 0x100a + B1800 = 0xa + B19200 = 0xe + B200 = 0x6 + B2000000 = 0x100b + B230400 = 0x1003 + B2400 = 0xb + B2500000 = 0x100c + B300 = 0x7 + B3000000 = 0x100d + B3500000 = 0x100e + B38400 = 0xf + B4000000 = 0x100f + B460800 = 0x1004 + B4800 = 0xc + B50 = 0x1 + B500000 = 0x1005 + B57600 = 0x1001 + B576000 = 0x1006 + B600 = 0x8 + B75 = 0x2 + B921600 = 0x1007 + B9600 = 0xd + BOTHER = 0x1000 + BPF_A = 0x10 + BPF_ABS = 0x20 + BPF_ADD = 0x0 + BPF_ALU = 0x4 + BPF_AND = 0x50 + BPF_B = 0x10 + BPF_DIV = 0x30 + BPF_H = 0x8 + BPF_IMM = 0x0 + BPF_IND = 0x40 + BPF_JA = 0x0 + BPF_JEQ = 0x10 + BPF_JGE = 0x30 + BPF_JGT = 0x20 + BPF_JMP = 0x5 + BPF_JSET = 0x40 + BPF_K = 0x0 + BPF_LD = 0x0 + BPF_LDX = 0x1 + BPF_LEN = 0x80 + BPF_LSH = 0x60 + BPF_MAJOR_VERSION = 0x1 + BPF_MAXINSNS = 0x1000 + BPF_MEM = 0x60 + BPF_MEMWORDS = 0x10 + BPF_MINOR_VERSION = 0x1 + BPF_MISC = 0x7 + BPF_MSH = 0xa0 + BPF_MUL = 0x20 + BPF_NEG = 0x80 + BPF_OR = 0x40 + BPF_RET = 0x6 + BPF_RSH = 0x70 + BPF_ST = 0x2 + BPF_STX = 0x3 + BPF_SUB = 0x10 + BPF_TAX = 0x0 + BPF_TXA = 0x80 + BPF_W = 0x0 + BPF_X = 0x8 + BRKINT = 0x2 + BS0 = 0x0 + BS1 = 0x2000 + BSDLY = 0x2000 + CAN_BCM = 0x2 + CAN_EFF_FLAG = 0x80000000 + CAN_EFF_MASK = 0x1fffffff + CAN_ERR_FLAG = 0x20000000 + CAN_ERR_MASK = 0x1fffffff + CAN_INV_FILTER = 0x20000000 + CAN_ISOTP = 0x6 + CAN_MCNET = 0x5 + CAN_NPROTO = 0x7 + CAN_RAW = 0x1 + CAN_RTR_FLAG = 0x40000000 + CAN_SFF_MASK = 0x7ff + CAN_TP16 = 0x3 + CAN_TP20 = 0x4 + CBAUD = 0x100f + CBAUDEX = 0x1000 + CFLUSH = 0xf + CIBAUD = 0x100f0000 + CLOCAL = 0x800 + CLOCK_DEFAULT = 0x0 + CLOCK_EXT = 0x1 + CLOCK_INT = 0x2 + CLOCK_MONOTONIC = 0x1 + CLOCK_MONOTONIC_COARSE = 0x6 + CLOCK_MONOTONIC_RAW = 0x4 + CLOCK_PROCESS_CPUTIME_ID = 0x2 + CLOCK_REALTIME = 0x0 + CLOCK_REALTIME_COARSE = 0x5 + CLOCK_THREAD_CPUTIME_ID = 0x3 + CLOCK_TXFROMRX = 0x4 + CLOCK_TXINT = 0x3 + CLONE_CHILD_CLEARTID = 0x200000 + CLONE_CHILD_SETTID = 0x1000000 + CLONE_DETACHED = 0x400000 + CLONE_FILES = 0x400 + CLONE_FS = 0x200 + CLONE_IO = 0x80000000 + CLONE_NEWIPC = 0x8000000 + CLONE_NEWNET = 0x40000000 + CLONE_NEWNS = 0x20000 + CLONE_NEWPID = 0x20000000 + CLONE_NEWUSER = 0x10000000 + CLONE_NEWUTS = 0x4000000 + CLONE_PARENT = 0x8000 + CLONE_PARENT_SETTID = 0x100000 + CLONE_PTRACE = 0x2000 + CLONE_SETTLS = 0x80000 + CLONE_SIGHAND = 0x800 + CLONE_SYSVSEM = 0x40000 + CLONE_THREAD = 0x10000 + CLONE_UNTRACED = 0x800000 + CLONE_VFORK = 0x4000 + CLONE_VM = 0x100 + CMSPAR = 0x40000000 + CR0 = 0x0 + CR1 = 0x200 + CR2 = 0x400 + CR3 = 0x600 + CRDLY = 0x600 + CREAD = 0x80 + CRTSCTS = 0x80000000 + CS5 = 0x0 + CS6 = 0x10 + CS7 = 0x20 + CS8 = 0x30 + CSIGNAL = 0xff + CSIZE = 0x30 + CSTART = 0x11 + CSTATUS = 0x0 + CSTOP = 0x13 + CSTOPB = 0x40 + CSUSP = 0x1a + DT_BLK = 0x6 + DT_CHR = 0x2 + DT_DIR = 0x4 + DT_FIFO = 0x1 + DT_LNK = 0xa + DT_REG = 0x8 + DT_SOCK = 0xc + DT_UNKNOWN = 0x0 + DT_WHT = 0xe + ECHO = 0x8 + ECHOCTL = 0x200 + ECHOE = 0x10 + ECHOK = 0x20 + ECHOKE = 0x800 + ECHONL = 0x40 + ECHOPRT = 0x400 + ENCODING_DEFAULT = 0x0 + ENCODING_FM_MARK = 0x3 + ENCODING_FM_SPACE = 0x4 + ENCODING_MANCHESTER = 0x5 + ENCODING_NRZ = 0x1 + ENCODING_NRZI = 0x2 + EPOLLERR = 0x8 + EPOLLET = -0x80000000 + EPOLLHUP = 0x10 + EPOLLIN = 0x1 + EPOLLMSG = 0x400 + EPOLLONESHOT = 0x40000000 + EPOLLOUT = 0x4 + EPOLLPRI = 0x2 + EPOLLRDBAND = 0x80 + EPOLLRDHUP = 0x2000 + EPOLLRDNORM = 0x40 + EPOLLWRBAND = 0x200 + EPOLLWRNORM = 0x100 + EPOLL_CLOEXEC = 0x80000 + EPOLL_CTL_ADD = 0x1 + EPOLL_CTL_DEL = 0x2 + EPOLL_CTL_MOD = 0x3 + EPOLL_NONBLOCK = 0x80 + ETH_P_1588 = 0x88f7 + ETH_P_8021AD = 0x88a8 + ETH_P_8021AH = 0x88e7 + ETH_P_8021Q = 0x8100 + ETH_P_802_2 = 0x4 + ETH_P_802_3 = 0x1 + ETH_P_AARP = 0x80f3 + ETH_P_AF_IUCV = 0xfbfb + ETH_P_ALL = 0x3 + ETH_P_AOE = 0x88a2 + ETH_P_ARCNET = 0x1a + ETH_P_ARP = 0x806 + ETH_P_ATALK = 0x809b + ETH_P_ATMFATE = 0x8884 + ETH_P_ATMMPOA = 0x884c + ETH_P_AX25 = 0x2 + ETH_P_BPQ = 0x8ff + ETH_P_CAIF = 0xf7 + ETH_P_CAN = 0xc + ETH_P_CONTROL = 0x16 + ETH_P_CUST = 0x6006 + ETH_P_DDCMP = 0x6 + ETH_P_DEC = 0x6000 + ETH_P_DIAG = 0x6005 + ETH_P_DNA_DL = 0x6001 + ETH_P_DNA_RC = 0x6002 + ETH_P_DNA_RT = 0x6003 + ETH_P_DSA = 0x1b + ETH_P_ECONET = 0x18 + ETH_P_EDSA = 0xdada + ETH_P_FCOE = 0x8906 + ETH_P_FIP = 0x8914 + ETH_P_HDLC = 0x19 + ETH_P_IEEE802154 = 0xf6 + ETH_P_IEEEPUP = 0xa00 + ETH_P_IEEEPUPAT = 0xa01 + ETH_P_IP = 0x800 + ETH_P_IPV6 = 0x86dd + ETH_P_IPX = 0x8137 + ETH_P_IRDA = 0x17 + ETH_P_LAT = 0x6004 + ETH_P_LINK_CTL = 0x886c + ETH_P_LOCALTALK = 0x9 + ETH_P_LOOP = 0x60 + ETH_P_MOBITEX = 0x15 + ETH_P_MPLS_MC = 0x8848 + ETH_P_MPLS_UC = 0x8847 + ETH_P_PAE = 0x888e + ETH_P_PAUSE = 0x8808 + ETH_P_PHONET = 0xf5 + ETH_P_PPPTALK = 0x10 + ETH_P_PPP_DISC = 0x8863 + ETH_P_PPP_MP = 0x8 + ETH_P_PPP_SES = 0x8864 + ETH_P_PUP = 0x200 + ETH_P_PUPAT = 0x201 + ETH_P_QINQ1 = 0x9100 + ETH_P_QINQ2 = 0x9200 + ETH_P_QINQ3 = 0x9300 + ETH_P_RARP = 0x8035 + ETH_P_SCA = 0x6007 + ETH_P_SLOW = 0x8809 + ETH_P_SNAP = 0x5 + ETH_P_TDLS = 0x890d + ETH_P_TEB = 0x6558 + ETH_P_TIPC = 0x88ca + ETH_P_TRAILER = 0x1c + ETH_P_TR_802_2 = 0x11 + ETH_P_WAN_PPP = 0x7 + ETH_P_WCCP = 0x883e + ETH_P_X25 = 0x805 + EXTA = 0xe + EXTB = 0xf + EXTPROC = 0x10000 + FD_CLOEXEC = 0x1 + FD_SETSIZE = 0x400 + FF0 = 0x0 + FF1 = 0x8000 + FFDLY = 0x8000 + FLUSHO = 0x2000 + F_DUPFD = 0x0 + F_DUPFD_CLOEXEC = 0x406 + F_EXLCK = 0x4 + F_GETFD = 0x1 + F_GETFL = 0x3 + F_GETLEASE = 0x401 + F_GETLK = 0x21 + F_GETLK64 = 0x21 + F_GETOWN = 0x17 + F_GETOWN_EX = 0x10 + F_GETPIPE_SZ = 0x408 + F_GETSIG = 0xb + F_LOCK = 0x1 + F_NOTIFY = 0x402 + F_OK = 0x0 + F_RDLCK = 0x0 + F_SETFD = 0x2 + F_SETFL = 0x4 + F_SETLEASE = 0x400 + F_SETLK = 0x22 + F_SETLK64 = 0x22 + F_SETLKW = 0x23 + F_SETLKW64 = 0x23 + F_SETOWN = 0x18 + F_SETOWN_EX = 0xf + F_SETPIPE_SZ = 0x407 + F_SETSIG = 0xa + F_SHLCK = 0x8 + F_TEST = 0x3 + F_TLOCK = 0x2 + F_ULOCK = 0x0 + F_UNLCK = 0x2 + F_WRLCK = 0x1 + HUPCL = 0x400 + IBSHIFT = 0x10 + ICANON = 0x2 + ICMPV6_FILTER = 0x1 + ICRNL = 0x100 + IEXTEN = 0x100 + IFA_F_DADFAILED = 0x8 + IFA_F_DEPRECATED = 0x20 + IFA_F_HOMEADDRESS = 0x10 + IFA_F_NODAD = 0x2 + IFA_F_OPTIMISTIC = 0x4 + IFA_F_PERMANENT = 0x80 + IFA_F_SECONDARY = 0x1 + IFA_F_TEMPORARY = 0x1 + IFA_F_TENTATIVE = 0x40 + IFA_MAX = 0x7 + IFF_802_1Q_VLAN = 0x1 + IFF_ALLMULTI = 0x200 + IFF_AUTOMEDIA = 0x4000 + IFF_BONDING = 0x20 + IFF_BRIDGE_PORT = 0x4000 + IFF_BROADCAST = 0x2 + IFF_DEBUG = 0x4 + IFF_DISABLE_NETPOLL = 0x1000 + IFF_DONT_BRIDGE = 0x800 + IFF_DORMANT = 0x20000 + IFF_DYNAMIC = 0x8000 + IFF_EBRIDGE = 0x2 + IFF_ECHO = 0x40000 + IFF_ISATAP = 0x80 + IFF_LOOPBACK = 0x8 + IFF_LOWER_UP = 0x10000 + IFF_MACVLAN_PORT = 0x2000 + IFF_MASTER = 0x400 + IFF_MASTER_8023AD = 0x8 + IFF_MASTER_ALB = 0x10 + IFF_MASTER_ARPMON = 0x100 + IFF_MULTICAST = 0x1000 + IFF_NOARP = 0x80 + IFF_NOTRAILERS = 0x20 + IFF_NO_PI = 0x1000 + IFF_ONE_QUEUE = 0x2000 + IFF_OVS_DATAPATH = 0x8000 + IFF_POINTOPOINT = 0x10 + IFF_PORTSEL = 0x2000 + IFF_PROMISC = 0x100 + IFF_RUNNING = 0x40 + IFF_SLAVE = 0x800 + IFF_SLAVE_INACTIVE = 0x4 + IFF_SLAVE_NEEDARP = 0x40 + IFF_TAP = 0x2 + IFF_TUN = 0x1 + IFF_TUN_EXCL = 0x8000 + IFF_TX_SKB_SHARING = 0x10000 + IFF_UNICAST_FLT = 0x20000 + IFF_UP = 0x1 + IFF_VNET_HDR = 0x4000 + IFF_VOLATILE = 0x70c5a + IFF_WAN_HDLC = 0x200 + IFF_XMIT_DST_RELEASE = 0x400 + IFNAMSIZ = 0x10 + IGNBRK = 0x1 + IGNCR = 0x80 + IGNPAR = 0x4 + IMAXBEL = 0x2000 + INLCR = 0x40 + INPCK = 0x10 + IN_ACCESS = 0x1 + IN_ALL_EVENTS = 0xfff + IN_ATTRIB = 0x4 + IN_CLASSA_HOST = 0xffffff + IN_CLASSA_MAX = 0x80 + IN_CLASSA_NET = 0xff000000 + IN_CLASSA_NSHIFT = 0x18 + IN_CLASSB_HOST = 0xffff + IN_CLASSB_MAX = 0x10000 + IN_CLASSB_NET = 0xffff0000 + IN_CLASSB_NSHIFT = 0x10 + IN_CLASSC_HOST = 0xff + IN_CLASSC_NET = 0xffffff00 + IN_CLASSC_NSHIFT = 0x8 + IN_CLOEXEC = 0x80000 + IN_CLOSE = 0x18 + IN_CLOSE_NOWRITE = 0x10 + IN_CLOSE_WRITE = 0x8 + IN_CREATE = 0x100 + IN_DELETE = 0x200 + IN_DELETE_SELF = 0x400 + IN_DONT_FOLLOW = 0x2000000 + IN_EXCL_UNLINK = 0x4000000 + IN_IGNORED = 0x8000 + IN_ISDIR = 0x40000000 + IN_LOOPBACKNET = 0x7f + IN_MASK_ADD = 0x20000000 + IN_MODIFY = 0x2 + IN_MOVE = 0xc0 + IN_MOVED_FROM = 0x40 + IN_MOVED_TO = 0x80 + IN_MOVE_SELF = 0x800 + IN_NONBLOCK = 0x80 + IN_ONESHOT = 0x80000000 + IN_ONLYDIR = 0x1000000 + IN_OPEN = 0x20 + IN_Q_OVERFLOW = 0x4000 + IN_UNMOUNT = 0x2000 + IPPROTO_AH = 0x33 + IPPROTO_COMP = 0x6c + IPPROTO_DCCP = 0x21 + IPPROTO_DSTOPTS = 0x3c + IPPROTO_EGP = 0x8 + IPPROTO_ENCAP = 0x62 + IPPROTO_ESP = 0x32 + IPPROTO_FRAGMENT = 0x2c + IPPROTO_GRE = 0x2f + IPPROTO_HOPOPTS = 0x0 + IPPROTO_ICMP = 0x1 + IPPROTO_ICMPV6 = 0x3a + IPPROTO_IDP = 0x16 + IPPROTO_IGMP = 0x2 + IPPROTO_IP = 0x0 + IPPROTO_IPIP = 0x4 + IPPROTO_IPV6 = 0x29 + IPPROTO_MTP = 0x5c + IPPROTO_NONE = 0x3b + IPPROTO_PIM = 0x67 + IPPROTO_PUP = 0xc + IPPROTO_RAW = 0xff + IPPROTO_ROUTING = 0x2b + IPPROTO_RSVP = 0x2e + IPPROTO_SCTP = 0x84 + IPPROTO_TCP = 0x6 + IPPROTO_TP = 0x1d + IPPROTO_UDP = 0x11 + IPPROTO_UDPLITE = 0x88 + IPV6_2292DSTOPTS = 0x4 + IPV6_2292HOPLIMIT = 0x8 + IPV6_2292HOPOPTS = 0x3 + IPV6_2292PKTINFO = 0x2 + IPV6_2292PKTOPTIONS = 0x6 + IPV6_2292RTHDR = 0x5 + IPV6_ADDRFORM = 0x1 + IPV6_ADD_MEMBERSHIP = 0x14 + IPV6_AUTHHDR = 0xa + IPV6_CHECKSUM = 0x7 + IPV6_DROP_MEMBERSHIP = 0x15 + IPV6_DSTOPTS = 0x3b + IPV6_HOPLIMIT = 0x34 + IPV6_HOPOPTS = 0x36 + IPV6_IPSEC_POLICY = 0x22 + IPV6_JOIN_ANYCAST = 0x1b + IPV6_JOIN_GROUP = 0x14 + IPV6_LEAVE_ANYCAST = 0x1c + IPV6_LEAVE_GROUP = 0x15 + IPV6_MTU = 0x18 + IPV6_MTU_DISCOVER = 0x17 + IPV6_MULTICAST_HOPS = 0x12 + IPV6_MULTICAST_IF = 0x11 + IPV6_MULTICAST_LOOP = 0x13 + IPV6_NEXTHOP = 0x9 + IPV6_PKTINFO = 0x32 + IPV6_PMTUDISC_DO = 0x2 + IPV6_PMTUDISC_DONT = 0x0 + IPV6_PMTUDISC_PROBE = 0x3 + IPV6_PMTUDISC_WANT = 0x1 + IPV6_RECVDSTOPTS = 0x3a + IPV6_RECVERR = 0x19 + IPV6_RECVHOPLIMIT = 0x33 + IPV6_RECVHOPOPTS = 0x35 + IPV6_RECVPKTINFO = 0x31 + IPV6_RECVRTHDR = 0x38 + IPV6_RECVTCLASS = 0x42 + IPV6_ROUTER_ALERT = 0x16 + IPV6_RTHDR = 0x39 + IPV6_RTHDRDSTOPTS = 0x37 + IPV6_RTHDR_LOOSE = 0x0 + IPV6_RTHDR_STRICT = 0x1 + IPV6_RTHDR_TYPE_0 = 0x0 + IPV6_RXDSTOPTS = 0x3b + IPV6_RXHOPOPTS = 0x36 + IPV6_TCLASS = 0x43 + IPV6_UNICAST_HOPS = 0x10 + IPV6_V6ONLY = 0x1a + IPV6_XFRM_POLICY = 0x23 + IP_ADD_MEMBERSHIP = 0x23 + IP_ADD_SOURCE_MEMBERSHIP = 0x27 + IP_BLOCK_SOURCE = 0x26 + IP_DEFAULT_MULTICAST_LOOP = 0x1 + IP_DEFAULT_MULTICAST_TTL = 0x1 + IP_DF = 0x4000 + IP_DROP_MEMBERSHIP = 0x24 + IP_DROP_SOURCE_MEMBERSHIP = 0x28 + IP_FREEBIND = 0xf + IP_HDRINCL = 0x3 + IP_IPSEC_POLICY = 0x10 + IP_MAXPACKET = 0xffff + IP_MAX_MEMBERSHIPS = 0x14 + IP_MF = 0x2000 + IP_MINTTL = 0x15 + IP_MSFILTER = 0x29 + IP_MSS = 0x240 + IP_MTU = 0xe + IP_MTU_DISCOVER = 0xa + IP_MULTICAST_IF = 0x20 + IP_MULTICAST_LOOP = 0x22 + IP_MULTICAST_TTL = 0x21 + IP_OFFMASK = 0x1fff + IP_OPTIONS = 0x4 + IP_ORIGDSTADDR = 0x14 + IP_PASSSEC = 0x12 + IP_PKTINFO = 0x8 + IP_PKTOPTIONS = 0x9 + IP_PMTUDISC = 0xa + IP_PMTUDISC_DO = 0x2 + IP_PMTUDISC_DONT = 0x0 + IP_PMTUDISC_PROBE = 0x3 + IP_PMTUDISC_WANT = 0x1 + IP_RECVERR = 0xb + IP_RECVOPTS = 0x6 + IP_RECVORIGDSTADDR = 0x14 + IP_RECVRETOPTS = 0x7 + IP_RECVTOS = 0xd + IP_RECVTTL = 0xc + IP_RETOPTS = 0x7 + IP_RF = 0x8000 + IP_ROUTER_ALERT = 0x5 + IP_TOS = 0x1 + IP_TRANSPARENT = 0x13 + IP_TTL = 0x2 + IP_UNBLOCK_SOURCE = 0x25 + IP_XFRM_POLICY = 0x11 + ISIG = 0x1 + ISTRIP = 0x20 + IUCLC = 0x200 + IUTF8 = 0x4000 + IXANY = 0x800 + IXOFF = 0x1000 + IXON = 0x400 + LINUX_REBOOT_CMD_CAD_OFF = 0x0 + LINUX_REBOOT_CMD_CAD_ON = 0x89abcdef + LINUX_REBOOT_CMD_HALT = 0xcdef0123 + LINUX_REBOOT_CMD_KEXEC = 0x45584543 + LINUX_REBOOT_CMD_POWER_OFF = 0x4321fedc + LINUX_REBOOT_CMD_RESTART = 0x1234567 + LINUX_REBOOT_CMD_RESTART2 = 0xa1b2c3d4 + LINUX_REBOOT_CMD_SW_SUSPEND = 0xd000fce2 + LINUX_REBOOT_MAGIC1 = 0xfee1dead + LINUX_REBOOT_MAGIC2 = 0x28121969 + LOCK_EX = 0x2 + LOCK_NB = 0x4 + LOCK_SH = 0x1 + LOCK_UN = 0x8 + MADV_DOFORK = 0xb + MADV_DONTFORK = 0xa + MADV_DONTNEED = 0x4 + MADV_HUGEPAGE = 0xe + MADV_HWPOISON = 0x64 + MADV_MERGEABLE = 0xc + MADV_NOHUGEPAGE = 0xf + MADV_NORMAL = 0x0 + MADV_RANDOM = 0x1 + MADV_REMOVE = 0x9 + MADV_SEQUENTIAL = 0x2 + MADV_UNMERGEABLE = 0xd + MADV_WILLNEED = 0x3 + MAP_ANON = 0x800 + MAP_ANONYMOUS = 0x800 + MAP_DENYWRITE = 0x2000 + MAP_EXECUTABLE = 0x4000 + MAP_FILE = 0x0 + MAP_FIXED = 0x10 + MAP_GROWSDOWN = 0x1000 + MAP_LOCKED = 0x8000 + MAP_NONBLOCK = 0x20000 + MAP_NORESERVE = 0x400 + MAP_POPULATE = 0x10000 + MAP_PRIVATE = 0x2 + MAP_RENAME = 0x800 + MAP_SHARED = 0x1 + MAP_TYPE = 0xf + MCL_CURRENT = 0x1 + MCL_FUTURE = 0x2 + MNT_DETACH = 0x2 + MNT_EXPIRE = 0x4 + MNT_FORCE = 0x1 + MSG_CMSG_CLOEXEC = 0x40000000 + MSG_CONFIRM = 0x800 + MSG_CTRUNC = 0x8 + MSG_DONTROUTE = 0x4 + MSG_DONTWAIT = 0x40 + MSG_EOR = 0x80 + MSG_ERRQUEUE = 0x2000 + MSG_FASTOPEN = 0x20000000 + MSG_FIN = 0x200 + MSG_MORE = 0x8000 + MSG_NOSIGNAL = 0x4000 + MSG_OOB = 0x1 + MSG_PEEK = 0x2 + MSG_PROXY = 0x10 + MSG_RST = 0x1000 + MSG_SYN = 0x400 + MSG_TRUNC = 0x20 + MSG_TRYHARD = 0x4 + MSG_WAITALL = 0x100 + MSG_WAITFORONE = 0x10000 + MS_ACTIVE = 0x40000000 + MS_ASYNC = 0x1 + MS_BIND = 0x1000 + MS_DIRSYNC = 0x80 + MS_INVALIDATE = 0x2 + MS_I_VERSION = 0x800000 + MS_KERNMOUNT = 0x400000 + MS_MANDLOCK = 0x40 + MS_MGC_MSK = 0xffff0000 + MS_MGC_VAL = 0xc0ed0000 + MS_MOVE = 0x2000 + MS_NOATIME = 0x400 + MS_NODEV = 0x4 + MS_NODIRATIME = 0x800 + MS_NOEXEC = 0x8 + MS_NOSUID = 0x2 + MS_NOUSER = -0x80000000 + MS_POSIXACL = 0x10000 + MS_PRIVATE = 0x40000 + MS_RDONLY = 0x1 + MS_REC = 0x4000 + MS_RELATIME = 0x200000 + MS_REMOUNT = 0x20 + MS_RMT_MASK = 0x800051 + MS_SHARED = 0x100000 + MS_SILENT = 0x8000 + MS_SLAVE = 0x80000 + MS_STRICTATIME = 0x1000000 + MS_SYNC = 0x4 + MS_SYNCHRONOUS = 0x10 + MS_UNBINDABLE = 0x20000 + NAME_MAX = 0xff + NETLINK_ADD_MEMBERSHIP = 0x1 + NETLINK_AUDIT = 0x9 + NETLINK_BROADCAST_ERROR = 0x4 + NETLINK_CONNECTOR = 0xb + NETLINK_CRYPTO = 0x15 + NETLINK_DNRTMSG = 0xe + NETLINK_DROP_MEMBERSHIP = 0x2 + NETLINK_ECRYPTFS = 0x13 + NETLINK_FIB_LOOKUP = 0xa + NETLINK_FIREWALL = 0x3 + NETLINK_GENERIC = 0x10 + NETLINK_INET_DIAG = 0x4 + NETLINK_IP6_FW = 0xd + NETLINK_ISCSI = 0x8 + NETLINK_KOBJECT_UEVENT = 0xf + NETLINK_NETFILTER = 0xc + NETLINK_NFLOG = 0x5 + NETLINK_NO_ENOBUFS = 0x5 + NETLINK_PKTINFO = 0x3 + NETLINK_RDMA = 0x14 + NETLINK_ROUTE = 0x0 + NETLINK_SCSITRANSPORT = 0x12 + NETLINK_SELINUX = 0x7 + NETLINK_UNUSED = 0x1 + NETLINK_USERSOCK = 0x2 + NETLINK_XFRM = 0x6 + NL0 = 0x0 + NL1 = 0x100 + NLA_ALIGNTO = 0x4 + NLA_F_NESTED = 0x8000 + NLA_F_NET_BYTEORDER = 0x4000 + NLA_HDRLEN = 0x4 + NLDLY = 0x100 + NLMSG_ALIGNTO = 0x4 + NLMSG_DONE = 0x3 + NLMSG_ERROR = 0x2 + NLMSG_HDRLEN = 0x10 + NLMSG_MIN_TYPE = 0x10 + NLMSG_NOOP = 0x1 + NLMSG_OVERRUN = 0x4 + NLM_F_ACK = 0x4 + NLM_F_APPEND = 0x800 + NLM_F_ATOMIC = 0x400 + NLM_F_CREATE = 0x400 + NLM_F_DUMP = 0x300 + NLM_F_DUMP_INTR = 0x10 + NLM_F_ECHO = 0x8 + NLM_F_EXCL = 0x200 + NLM_F_MATCH = 0x200 + NLM_F_MULTI = 0x2 + NLM_F_REPLACE = 0x100 + NLM_F_REQUEST = 0x1 + NLM_F_ROOT = 0x100 + NOFLSH = 0x80 + OCRNL = 0x8 + OFDEL = 0x80 + OFILL = 0x40 + OLCUC = 0x2 + ONLCR = 0x4 + ONLRET = 0x20 + ONOCR = 0x10 + OPOST = 0x1 + O_ACCMODE = 0x3 + O_APPEND = 0x8 + O_ASYNC = 0x1000 + O_CLOEXEC = 0x80000 + O_CREAT = 0x100 + O_DIRECT = 0x8000 + O_DIRECTORY = 0x10000 + O_DSYNC = 0x10 + O_EXCL = 0x400 + O_FSYNC = 0x4010 + O_LARGEFILE = 0x2000 + O_NDELAY = 0x80 + O_NOATIME = 0x40000 + O_NOCTTY = 0x800 + O_NOFOLLOW = 0x20000 + O_NONBLOCK = 0x80 + O_RDONLY = 0x0 + O_RDWR = 0x2 + O_RSYNC = 0x4010 + O_SYNC = 0x4010 + O_TRUNC = 0x200 + O_WRONLY = 0x1 + PACKET_ADD_MEMBERSHIP = 0x1 + PACKET_AUXDATA = 0x8 + PACKET_BROADCAST = 0x1 + PACKET_COPY_THRESH = 0x7 + PACKET_DROP_MEMBERSHIP = 0x2 + PACKET_FANOUT = 0x12 + PACKET_FANOUT_CPU = 0x2 + PACKET_FANOUT_FLAG_DEFRAG = 0x8000 + PACKET_FANOUT_HASH = 0x0 + PACKET_FANOUT_LB = 0x1 + PACKET_FASTROUTE = 0x6 + PACKET_HDRLEN = 0xb + PACKET_HOST = 0x0 + PACKET_LOOPBACK = 0x5 + PACKET_LOSS = 0xe + PACKET_MR_ALLMULTI = 0x2 + PACKET_MR_MULTICAST = 0x0 + PACKET_MR_PROMISC = 0x1 + PACKET_MR_UNICAST = 0x3 + PACKET_MULTICAST = 0x2 + PACKET_ORIGDEV = 0x9 + PACKET_OTHERHOST = 0x3 + PACKET_OUTGOING = 0x4 + PACKET_RECV_OUTPUT = 0x3 + PACKET_RESERVE = 0xc + PACKET_RX_RING = 0x5 + PACKET_STATISTICS = 0x6 + PACKET_TIMESTAMP = 0x11 + PACKET_TX_RING = 0xd + PACKET_TX_TIMESTAMP = 0x10 + PACKET_VERSION = 0xa + PACKET_VNET_HDR = 0xf + PARENB = 0x100 + PARITY_CRC16_PR0 = 0x2 + PARITY_CRC16_PR0_CCITT = 0x4 + PARITY_CRC16_PR1 = 0x3 + PARITY_CRC16_PR1_CCITT = 0x5 + PARITY_CRC32_PR0_CCITT = 0x6 + PARITY_CRC32_PR1_CCITT = 0x7 + PARITY_DEFAULT = 0x0 + PARITY_NONE = 0x1 + PARMRK = 0x8 + PARODD = 0x200 + PENDIN = 0x4000 + PRIO_PGRP = 0x1 + PRIO_PROCESS = 0x0 + PRIO_USER = 0x2 + PROT_EXEC = 0x4 + PROT_GROWSDOWN = 0x1000000 + PROT_GROWSUP = 0x2000000 + PROT_NONE = 0x0 + PROT_READ = 0x1 + PROT_WRITE = 0x2 + PR_CAPBSET_DROP = 0x18 + PR_CAPBSET_READ = 0x17 + PR_ENDIAN_BIG = 0x0 + PR_ENDIAN_LITTLE = 0x1 + PR_ENDIAN_PPC_LITTLE = 0x2 + PR_FPEMU_NOPRINT = 0x1 + PR_FPEMU_SIGFPE = 0x2 + PR_FP_EXC_ASYNC = 0x2 + PR_FP_EXC_DISABLED = 0x0 + PR_FP_EXC_DIV = 0x10000 + PR_FP_EXC_INV = 0x100000 + PR_FP_EXC_NONRECOV = 0x1 + PR_FP_EXC_OVF = 0x20000 + PR_FP_EXC_PRECISE = 0x3 + PR_FP_EXC_RES = 0x80000 + PR_FP_EXC_SW_ENABLE = 0x80 + PR_FP_EXC_UND = 0x40000 + PR_GET_DUMPABLE = 0x3 + PR_GET_ENDIAN = 0x13 + PR_GET_FPEMU = 0x9 + PR_GET_FPEXC = 0xb + PR_GET_KEEPCAPS = 0x7 + PR_GET_NAME = 0x10 + PR_GET_PDEATHSIG = 0x2 + PR_GET_SECCOMP = 0x15 + PR_GET_SECUREBITS = 0x1b + PR_GET_TIMERSLACK = 0x1e + PR_GET_TIMING = 0xd + PR_GET_TSC = 0x19 + PR_GET_UNALIGN = 0x5 + PR_MCE_KILL = 0x21 + PR_MCE_KILL_CLEAR = 0x0 + PR_MCE_KILL_DEFAULT = 0x2 + PR_MCE_KILL_EARLY = 0x1 + PR_MCE_KILL_GET = 0x22 + PR_MCE_KILL_LATE = 0x0 + PR_MCE_KILL_SET = 0x1 + PR_SET_DUMPABLE = 0x4 + PR_SET_ENDIAN = 0x14 + PR_SET_FPEMU = 0xa + PR_SET_FPEXC = 0xc + PR_SET_KEEPCAPS = 0x8 + PR_SET_NAME = 0xf + PR_SET_PDEATHSIG = 0x1 + PR_SET_SECCOMP = 0x16 + PR_SET_SECUREBITS = 0x1c + PR_SET_TIMERSLACK = 0x1d + PR_SET_TIMING = 0xe + PR_SET_TSC = 0x1a + PR_SET_UNALIGN = 0x6 + PR_TASK_PERF_EVENTS_DISABLE = 0x1f + PR_TASK_PERF_EVENTS_ENABLE = 0x20 + PR_TIMING_STATISTICAL = 0x0 + PR_TIMING_TIMESTAMP = 0x1 + PR_TSC_ENABLE = 0x1 + PR_TSC_SIGSEGV = 0x2 + PR_UNALIGN_NOPRINT = 0x1 + PR_UNALIGN_SIGBUS = 0x2 + PTRACE_ATTACH = 0x10 + PTRACE_CONT = 0x7 + PTRACE_DETACH = 0x11 + PTRACE_EVENT_CLONE = 0x3 + PTRACE_EVENT_EXEC = 0x4 + PTRACE_EVENT_EXIT = 0x6 + PTRACE_EVENT_FORK = 0x1 + PTRACE_EVENT_STOP = 0x7 + PTRACE_EVENT_VFORK = 0x2 + PTRACE_EVENT_VFORK_DONE = 0x5 + PTRACE_GETEVENTMSG = 0x4201 + PTRACE_GETFPREGS = 0xe + PTRACE_GETREGS = 0xc + PTRACE_GETREGSET = 0x4204 + PTRACE_GETSIGINFO = 0x4202 + PTRACE_GET_THREAD_AREA = 0x19 + PTRACE_GET_THREAD_AREA_3264 = 0xc4 + PTRACE_GET_WATCH_REGS = 0xd0 + PTRACE_INTERRUPT = 0x4207 + PTRACE_KILL = 0x8 + PTRACE_LISTEN = 0x4208 + PTRACE_OLDSETOPTIONS = 0x15 + PTRACE_O_MASK = 0x7f + PTRACE_O_TRACECLONE = 0x8 + PTRACE_O_TRACEEXEC = 0x10 + PTRACE_O_TRACEEXIT = 0x40 + PTRACE_O_TRACEFORK = 0x2 + PTRACE_O_TRACESYSGOOD = 0x1 + PTRACE_O_TRACEVFORK = 0x4 + PTRACE_O_TRACEVFORKDONE = 0x20 + PTRACE_PEEKDATA = 0x2 + PTRACE_PEEKDATA_3264 = 0xc1 + PTRACE_PEEKTEXT = 0x1 + PTRACE_PEEKTEXT_3264 = 0xc0 + PTRACE_PEEKUSR = 0x3 + PTRACE_POKEDATA = 0x5 + PTRACE_POKEDATA_3264 = 0xc3 + PTRACE_POKETEXT = 0x4 + PTRACE_POKETEXT_3264 = 0xc2 + PTRACE_POKEUSR = 0x6 + PTRACE_SEIZE = 0x4206 + PTRACE_SEIZE_DEVEL = 0x80000000 + PTRACE_SETFPREGS = 0xf + PTRACE_SETOPTIONS = 0x4200 + PTRACE_SETREGS = 0xd + PTRACE_SETREGSET = 0x4205 + PTRACE_SETSIGINFO = 0x4203 + PTRACE_SET_THREAD_AREA = 0x1a + PTRACE_SET_WATCH_REGS = 0xd1 + PTRACE_SINGLESTEP = 0x9 + PTRACE_SYSCALL = 0x18 + PTRACE_TRACEME = 0x0 + RLIMIT_AS = 0x6 + RLIMIT_CORE = 0x4 + RLIMIT_CPU = 0x0 + RLIMIT_DATA = 0x2 + RLIMIT_FSIZE = 0x1 + RLIMIT_NOFILE = 0x5 + RLIMIT_STACK = 0x3 + RLIM_INFINITY = 0x7fffffffffffffff + RTAX_ADVMSS = 0x8 + RTAX_CWND = 0x7 + RTAX_FEATURES = 0xc + RTAX_FEATURE_ALLFRAG = 0x8 + RTAX_FEATURE_ECN = 0x1 + RTAX_FEATURE_SACK = 0x2 + RTAX_FEATURE_TIMESTAMP = 0x4 + RTAX_HOPLIMIT = 0xa + RTAX_INITCWND = 0xb + RTAX_INITRWND = 0xe + RTAX_LOCK = 0x1 + RTAX_MAX = 0xe + RTAX_MTU = 0x2 + RTAX_REORDERING = 0x9 + RTAX_RTO_MIN = 0xd + RTAX_RTT = 0x4 + RTAX_RTTVAR = 0x5 + RTAX_SSTHRESH = 0x6 + RTAX_UNSPEC = 0x0 + RTAX_WINDOW = 0x3 + RTA_ALIGNTO = 0x4 + RTA_MAX = 0x10 + RTCF_DIRECTSRC = 0x4000000 + RTCF_DOREDIRECT = 0x1000000 + RTCF_LOG = 0x2000000 + RTCF_MASQ = 0x400000 + RTCF_NAT = 0x800000 + RTCF_VALVE = 0x200000 + RTF_ADDRCLASSMASK = 0xf8000000 + RTF_ADDRCONF = 0x40000 + RTF_ALLONLINK = 0x20000 + RTF_BROADCAST = 0x10000000 + RTF_CACHE = 0x1000000 + RTF_DEFAULT = 0x10000 + RTF_DYNAMIC = 0x10 + RTF_FLOW = 0x2000000 + RTF_GATEWAY = 0x2 + RTF_HOST = 0x4 + RTF_INTERFACE = 0x40000000 + RTF_IRTT = 0x100 + RTF_LINKRT = 0x100000 + RTF_LOCAL = 0x80000000 + RTF_MODIFIED = 0x20 + RTF_MSS = 0x40 + RTF_MTU = 0x40 + RTF_MULTICAST = 0x20000000 + RTF_NAT = 0x8000000 + RTF_NOFORWARD = 0x1000 + RTF_NONEXTHOP = 0x200000 + RTF_NOPMTUDISC = 0x4000 + RTF_POLICY = 0x4000000 + RTF_REINSTATE = 0x8 + RTF_REJECT = 0x200 + RTF_STATIC = 0x400 + RTF_THROW = 0x2000 + RTF_UP = 0x1 + RTF_WINDOW = 0x80 + RTF_XRESOLVE = 0x800 + RTM_BASE = 0x10 + RTM_DELACTION = 0x31 + RTM_DELADDR = 0x15 + RTM_DELADDRLABEL = 0x49 + RTM_DELLINK = 0x11 + RTM_DELNEIGH = 0x1d + RTM_DELQDISC = 0x25 + RTM_DELROUTE = 0x19 + RTM_DELRULE = 0x21 + RTM_DELTCLASS = 0x29 + RTM_DELTFILTER = 0x2d + RTM_F_CLONED = 0x200 + RTM_F_EQUALIZE = 0x400 + RTM_F_NOTIFY = 0x100 + RTM_F_PREFIX = 0x800 + RTM_GETACTION = 0x32 + RTM_GETADDR = 0x16 + RTM_GETADDRLABEL = 0x4a + RTM_GETANYCAST = 0x3e + RTM_GETDCB = 0x4e + RTM_GETLINK = 0x12 + RTM_GETMULTICAST = 0x3a + RTM_GETNEIGH = 0x1e + RTM_GETNEIGHTBL = 0x42 + RTM_GETQDISC = 0x26 + RTM_GETROUTE = 0x1a + RTM_GETRULE = 0x22 + RTM_GETTCLASS = 0x2a + RTM_GETTFILTER = 0x2e + RTM_MAX = 0x4f + RTM_NEWACTION = 0x30 + RTM_NEWADDR = 0x14 + RTM_NEWADDRLABEL = 0x48 + RTM_NEWLINK = 0x10 + RTM_NEWNDUSEROPT = 0x44 + RTM_NEWNEIGH = 0x1c + RTM_NEWNEIGHTBL = 0x40 + RTM_NEWPREFIX = 0x34 + RTM_NEWQDISC = 0x24 + RTM_NEWROUTE = 0x18 + RTM_NEWRULE = 0x20 + RTM_NEWTCLASS = 0x28 + RTM_NEWTFILTER = 0x2c + RTM_NR_FAMILIES = 0x10 + RTM_NR_MSGTYPES = 0x40 + RTM_SETDCB = 0x4f + RTM_SETLINK = 0x13 + RTM_SETNEIGHTBL = 0x43 + RTNH_ALIGNTO = 0x4 + RTNH_F_DEAD = 0x1 + RTNH_F_ONLINK = 0x4 + RTNH_F_PERVASIVE = 0x2 + RTN_MAX = 0xb + RTPROT_BIRD = 0xc + RTPROT_BOOT = 0x3 + RTPROT_DHCP = 0x10 + RTPROT_DNROUTED = 0xd + RTPROT_GATED = 0x8 + RTPROT_KERNEL = 0x2 + RTPROT_MRT = 0xa + RTPROT_NTK = 0xf + RTPROT_RA = 0x9 + RTPROT_REDIRECT = 0x1 + RTPROT_STATIC = 0x4 + RTPROT_UNSPEC = 0x0 + RTPROT_XORP = 0xe + RTPROT_ZEBRA = 0xb + RT_CLASS_DEFAULT = 0xfd + RT_CLASS_LOCAL = 0xff + RT_CLASS_MAIN = 0xfe + RT_CLASS_MAX = 0xff + RT_CLASS_UNSPEC = 0x0 + RUSAGE_CHILDREN = -0x1 + RUSAGE_SELF = 0x0 + RUSAGE_THREAD = 0x1 + SCM_CREDENTIALS = 0x2 + SCM_RIGHTS = 0x1 + SCM_TIMESTAMP = 0x1d + SCM_TIMESTAMPING = 0x25 + SCM_TIMESTAMPNS = 0x23 + SHUT_RD = 0x0 + SHUT_RDWR = 0x2 + SHUT_WR = 0x1 + SIOCADDDLCI = 0x8980 + SIOCADDMULTI = 0x8931 + SIOCADDRT = 0x890b + SIOCATMARK = 0x40047307 + SIOCDARP = 0x8953 + SIOCDELDLCI = 0x8981 + SIOCDELMULTI = 0x8932 + SIOCDELRT = 0x890c + SIOCDEVPRIVATE = 0x89f0 + SIOCDIFADDR = 0x8936 + SIOCDRARP = 0x8960 + SIOCGARP = 0x8954 + SIOCGIFADDR = 0x8915 + SIOCGIFBR = 0x8940 + SIOCGIFBRDADDR = 0x8919 + SIOCGIFCONF = 0x8912 + SIOCGIFCOUNT = 0x8938 + SIOCGIFDSTADDR = 0x8917 + SIOCGIFENCAP = 0x8925 + SIOCGIFFLAGS = 0x8913 + SIOCGIFHWADDR = 0x8927 + SIOCGIFINDEX = 0x8933 + SIOCGIFMAP = 0x8970 + SIOCGIFMEM = 0x891f + SIOCGIFMETRIC = 0x891d + SIOCGIFMTU = 0x8921 + SIOCGIFNAME = 0x8910 + SIOCGIFNETMASK = 0x891b + SIOCGIFPFLAGS = 0x8935 + SIOCGIFSLAVE = 0x8929 + SIOCGIFTXQLEN = 0x8942 + SIOCGPGRP = 0x40047309 + SIOCGRARP = 0x8961 + SIOCGSTAMP = 0x8906 + SIOCGSTAMPNS = 0x8907 + SIOCPROTOPRIVATE = 0x89e0 + SIOCRTMSG = 0x890d + SIOCSARP = 0x8955 + SIOCSIFADDR = 0x8916 + SIOCSIFBR = 0x8941 + SIOCSIFBRDADDR = 0x891a + SIOCSIFDSTADDR = 0x8918 + SIOCSIFENCAP = 0x8926 + SIOCSIFFLAGS = 0x8914 + SIOCSIFHWADDR = 0x8924 + SIOCSIFHWBROADCAST = 0x8937 + SIOCSIFLINK = 0x8911 + SIOCSIFMAP = 0x8971 + SIOCSIFMEM = 0x8920 + SIOCSIFMETRIC = 0x891e + SIOCSIFMTU = 0x8922 + SIOCSIFNAME = 0x8923 + SIOCSIFNETMASK = 0x891c + SIOCSIFPFLAGS = 0x8934 + SIOCSIFSLAVE = 0x8930 + SIOCSIFTXQLEN = 0x8943 + SIOCSPGRP = 0x80047308 + SIOCSRARP = 0x8962 + SOCK_CLOEXEC = 0x80000 + SOCK_DCCP = 0x6 + SOCK_DGRAM = 0x1 + SOCK_NONBLOCK = 0x80 + SOCK_PACKET = 0xa + SOCK_RAW = 0x3 + SOCK_RDM = 0x4 + SOCK_SEQPACKET = 0x5 + SOCK_STREAM = 0x2 + SOL_AAL = 0x109 + SOL_ATM = 0x108 + SOL_CAN_BASE = 0x64 + SOL_DECNET = 0x105 + SOL_ICMPV6 = 0x3a + SOL_IP = 0x0 + SOL_IPV6 = 0x29 + SOL_IRDA = 0x10a + SOL_PACKET = 0x107 + SOL_RAW = 0xff + SOL_SOCKET = 0xffff + SOL_TCP = 0x6 + SOL_X25 = 0x106 + SOMAXCONN = 0x80 + SO_ACCEPTCONN = 0x1009 + SO_ATTACH_FILTER = 0x1a + SO_BINDTODEVICE = 0x19 + SO_BROADCAST = 0x20 + SO_BSDCOMPAT = 0xe + SO_DEBUG = 0x1 + SO_DETACH_FILTER = 0x1b + SO_DOMAIN = 0x1029 + SO_DONTROUTE = 0x10 + SO_ERROR = 0x1007 + SO_KEEPALIVE = 0x8 + SO_LINGER = 0x80 + SO_MARK = 0x24 + SO_NO_CHECK = 0xb + SO_OOBINLINE = 0x100 + SO_PASSCRED = 0x11 + SO_PASSSEC = 0x22 + SO_PEERCRED = 0x12 + SO_PEERNAME = 0x1c + SO_PEERSEC = 0x1e + SO_PRIORITY = 0xc + SO_PROTOCOL = 0x1028 + SO_RCVBUF = 0x1002 + SO_RCVBUFFORCE = 0x21 + SO_RCVLOWAT = 0x1004 + SO_RCVTIMEO = 0x1006 + SO_REUSEADDR = 0x4 + SO_RXQ_OVFL = 0x28 + SO_SECURITY_AUTHENTICATION = 0x16 + SO_SECURITY_ENCRYPTION_NETWORK = 0x18 + SO_SECURITY_ENCRYPTION_TRANSPORT = 0x17 + SO_SNDBUF = 0x1001 + SO_SNDBUFFORCE = 0x1f + SO_SNDLOWAT = 0x1003 + SO_SNDTIMEO = 0x1005 + SO_STYLE = 0x1008 + SO_TIMESTAMP = 0x1d + SO_TIMESTAMPING = 0x25 + SO_TIMESTAMPNS = 0x23 + SO_TYPE = 0x1008 + S_BLKSIZE = 0x200 + S_IEXEC = 0x40 + S_IFBLK = 0x6000 + S_IFCHR = 0x2000 + S_IFDIR = 0x4000 + S_IFIFO = 0x1000 + S_IFLNK = 0xa000 + S_IFMT = 0xf000 + S_IFREG = 0x8000 + S_IFSOCK = 0xc000 + S_IREAD = 0x100 + S_IRGRP = 0x20 + S_IROTH = 0x4 + S_IRUSR = 0x100 + S_IRWXG = 0x38 + S_IRWXO = 0x7 + S_IRWXU = 0x1c0 + S_ISGID = 0x400 + S_ISUID = 0x800 + S_ISVTX = 0x200 + S_IWGRP = 0x10 + S_IWOTH = 0x2 + S_IWRITE = 0x80 + S_IWUSR = 0x80 + S_IXGRP = 0x8 + S_IXOTH = 0x1 + S_IXUSR = 0x40 + TAB0 = 0x0 + TAB1 = 0x800 + TAB2 = 0x1000 + TAB3 = 0x1800 + TABDLY = 0x1800 + TCFLSH = 0x5407 + TCGETA = 0x5401 + TCGETS = 0x540d + TCGETS2 = 0x4030542a + TCIFLUSH = 0x0 + TCIOFF = 0x2 + TCIOFLUSH = 0x2 + TCION = 0x3 + TCOFLUSH = 0x1 + TCOOFF = 0x0 + TCOON = 0x1 + TCP_CONGESTION = 0xd + TCP_CORK = 0x3 + TCP_DEFER_ACCEPT = 0x9 + TCP_INFO = 0xb + TCP_KEEPCNT = 0x6 + TCP_KEEPIDLE = 0x4 + TCP_KEEPINTVL = 0x5 + TCP_LINGER2 = 0x8 + TCP_MAXSEG = 0x2 + TCP_MAXWIN = 0xffff + TCP_MAX_WINSHIFT = 0xe + TCP_MD5SIG = 0xe + TCP_MD5SIG_MAXKEYLEN = 0x50 + TCP_MSS = 0x200 + TCP_NODELAY = 0x1 + TCP_QUICKACK = 0xc + TCP_SYNCNT = 0x7 + TCP_WINDOW_CLAMP = 0xa + TCSAFLUSH = 0x5410 + TCSBRK = 0x5405 + TCSBRKP = 0x5486 + TCSETA = 0x5402 + TCSETAF = 0x5404 + TCSETAW = 0x5403 + TCSETS = 0x540e + TCSETS2 = 0x8030542b + TCSETSF = 0x5410 + TCSETSF2 = 0x8030542d + TCSETSW = 0x540f + TCSETSW2 = 0x8030542c + TCXONC = 0x5406 + TIOCCBRK = 0x5428 + TIOCCONS = 0x80047478 + TIOCEXCL = 0x740d + TIOCGDEV = 0x40045432 + TIOCGETD = 0x7400 + TIOCGETP = 0x7408 + TIOCGICOUNT = 0x5492 + TIOCGLCKTRMIOS = 0x548b + TIOCGLTC = 0x7474 + TIOCGPGRP = 0x40047477 + TIOCGPTN = 0x40045430 + TIOCGSERIAL = 0x5484 + TIOCGSID = 0x7416 + TIOCGSOFTCAR = 0x5481 + TIOCGWINSZ = 0x40087468 + TIOCINQ = 0x467f + TIOCLINUX = 0x5483 + TIOCMBIC = 0x741c + TIOCMBIS = 0x741b + TIOCMGET = 0x741d + TIOCMIWAIT = 0x5491 + TIOCMSET = 0x741a + TIOCM_CAR = 0x100 + TIOCM_CD = 0x100 + TIOCM_CTS = 0x40 + TIOCM_DSR = 0x400 + TIOCM_DTR = 0x2 + TIOCM_LE = 0x1 + TIOCM_RI = 0x200 + TIOCM_RNG = 0x200 + TIOCM_RTS = 0x4 + TIOCM_SR = 0x20 + TIOCM_ST = 0x10 + TIOCNOTTY = 0x5471 + TIOCNXCL = 0x740e + TIOCOUTQ = 0x7472 + TIOCPKT = 0x5470 + TIOCPKT_DATA = 0x0 + TIOCPKT_DOSTOP = 0x20 + TIOCPKT_FLUSHREAD = 0x1 + TIOCPKT_FLUSHWRITE = 0x2 + TIOCPKT_IOCTL = 0x40 + TIOCPKT_NOSTOP = 0x10 + TIOCPKT_START = 0x8 + TIOCPKT_STOP = 0x4 + TIOCSBRK = 0x5427 + TIOCSCTTY = 0x5480 + TIOCSERCONFIG = 0x5488 + TIOCSERGETLSR = 0x548e + TIOCSERGETMULTI = 0x548f + TIOCSERGSTRUCT = 0x548d + TIOCSERGWILD = 0x5489 + TIOCSERSETMULTI = 0x5490 + TIOCSERSWILD = 0x548a + TIOCSER_TEMT = 0x1 + TIOCSETD = 0x7401 + TIOCSETN = 0x740a + TIOCSETP = 0x7409 + TIOCSIG = 0x80045436 + TIOCSLCKTRMIOS = 0x548c + TIOCSLTC = 0x7475 + TIOCSPGRP = 0x80047476 + TIOCSPTLCK = 0x80045431 + TIOCSSERIAL = 0x5485 + TIOCSSOFTCAR = 0x5482 + TIOCSTI = 0x5472 + TIOCSWINSZ = 0x80087467 + TIOCVHANGUP = 0x5437 + TOSTOP = 0x8000 + TUNATTACHFILTER = 0x800854d5 + TUNDETACHFILTER = 0x800854d6 + TUNGETFEATURES = 0x400454cf + TUNGETIFF = 0x400454d2 + TUNGETSNDBUF = 0x400454d3 + TUNGETVNETHDRSZ = 0x400454d7 + TUNSETDEBUG = 0x800454c9 + TUNSETGROUP = 0x800454ce + TUNSETIFF = 0x800454ca + TUNSETLINK = 0x800454cd + TUNSETNOCSUM = 0x800454c8 + TUNSETOFFLOAD = 0x800454d0 + TUNSETOWNER = 0x800454cc + TUNSETPERSIST = 0x800454cb + TUNSETSNDBUF = 0x800454d4 + TUNSETTXFILTER = 0x800454d1 + TUNSETVNETHDRSZ = 0x800454d8 + VDISCARD = 0xd + VEOF = 0x10 + VEOL = 0x11 + VEOL2 = 0x6 + VERASE = 0x2 + VINTR = 0x0 + VKILL = 0x3 + VLNEXT = 0xf + VMIN = 0x4 + VQUIT = 0x1 + VREPRINT = 0xc + VSTART = 0x8 + VSTOP = 0x9 + VSUSP = 0xa + VSWTC = 0x7 + VSWTCH = 0x7 + VT0 = 0x0 + VT1 = 0x4000 + VTDLY = 0x4000 + VTIME = 0x5 + VWERASE = 0xe + WALL = 0x40000000 + WCLONE = 0x80000000 + WCONTINUED = 0x8 + WEXITED = 0x4 + WNOHANG = 0x1 + WNOTHREAD = 0x20000000 + WNOWAIT = 0x1000000 + WORDSIZE = 0x20 + WSTOPPED = 0x2 + WUNTRACED = 0x2 + XCASE = 0x4 + XTABS = 0x1800 +) + +// Errors +const ( + E2BIG = syscall.Errno(0x7) + EACCES = syscall.Errno(0xd) + EADDRINUSE = syscall.Errno(0x7d) + EADDRNOTAVAIL = syscall.Errno(0x7e) + EADV = syscall.Errno(0x44) + EAFNOSUPPORT = syscall.Errno(0x7c) + EAGAIN = syscall.Errno(0xb) + EALREADY = syscall.Errno(0x95) + EBADE = syscall.Errno(0x32) + EBADF = syscall.Errno(0x9) + EBADFD = syscall.Errno(0x51) + EBADMSG = syscall.Errno(0x4d) + EBADR = syscall.Errno(0x33) + EBADRQC = syscall.Errno(0x36) + EBADSLT = syscall.Errno(0x37) + EBFONT = syscall.Errno(0x3b) + EBUSY = syscall.Errno(0x10) + ECANCELED = syscall.Errno(0x9e) + ECHILD = syscall.Errno(0xa) + ECHRNG = syscall.Errno(0x25) + ECOMM = syscall.Errno(0x46) + ECONNABORTED = syscall.Errno(0x82) + ECONNREFUSED = syscall.Errno(0x92) + ECONNRESET = syscall.Errno(0x83) + EDEADLK = syscall.Errno(0x2d) + EDEADLOCK = syscall.Errno(0x38) + EDESTADDRREQ = syscall.Errno(0x60) + EDOM = syscall.Errno(0x21) + EDOTDOT = syscall.Errno(0x49) + EDQUOT = syscall.Errno(0x46d) + EEXIST = syscall.Errno(0x11) + EFAULT = syscall.Errno(0xe) + EFBIG = syscall.Errno(0x1b) + EHOSTDOWN = syscall.Errno(0x93) + EHOSTUNREACH = syscall.Errno(0x94) + EHWPOISON = syscall.Errno(0xa8) + EIDRM = syscall.Errno(0x24) + EILSEQ = syscall.Errno(0x58) + EINIT = syscall.Errno(0x8d) + EINPROGRESS = syscall.Errno(0x96) + EINTR = syscall.Errno(0x4) + EINVAL = syscall.Errno(0x16) + EIO = syscall.Errno(0x5) + EISCONN = syscall.Errno(0x85) + EISDIR = syscall.Errno(0x15) + EISNAM = syscall.Errno(0x8b) + EKEYEXPIRED = syscall.Errno(0xa2) + EKEYREJECTED = syscall.Errno(0xa4) + EKEYREVOKED = syscall.Errno(0xa3) + EL2HLT = syscall.Errno(0x2c) + EL2NSYNC = syscall.Errno(0x26) + EL3HLT = syscall.Errno(0x27) + EL3RST = syscall.Errno(0x28) + ELIBACC = syscall.Errno(0x53) + ELIBBAD = syscall.Errno(0x54) + ELIBEXEC = syscall.Errno(0x57) + ELIBMAX = syscall.Errno(0x56) + ELIBSCN = syscall.Errno(0x55) + ELNRNG = syscall.Errno(0x29) + ELOOP = syscall.Errno(0x5a) + EMEDIUMTYPE = syscall.Errno(0xa0) + EMFILE = syscall.Errno(0x18) + EMLINK = syscall.Errno(0x1f) + EMSGSIZE = syscall.Errno(0x61) + EMULTIHOP = syscall.Errno(0x4a) + ENAMETOOLONG = syscall.Errno(0x4e) + ENAVAIL = syscall.Errno(0x8a) + ENETDOWN = syscall.Errno(0x7f) + ENETRESET = syscall.Errno(0x81) + ENETUNREACH = syscall.Errno(0x80) + ENFILE = syscall.Errno(0x17) + ENOANO = syscall.Errno(0x35) + ENOBUFS = syscall.Errno(0x84) + ENOCSI = syscall.Errno(0x2b) + ENODATA = syscall.Errno(0x3d) + ENODEV = syscall.Errno(0x13) + ENOENT = syscall.Errno(0x2) + ENOEXEC = syscall.Errno(0x8) + ENOKEY = syscall.Errno(0xa1) + ENOLCK = syscall.Errno(0x2e) + ENOLINK = syscall.Errno(0x43) + ENOMEDIUM = syscall.Errno(0x9f) + ENOMEM = syscall.Errno(0xc) + ENOMSG = syscall.Errno(0x23) + ENONET = syscall.Errno(0x40) + ENOPKG = syscall.Errno(0x41) + ENOPROTOOPT = syscall.Errno(0x63) + ENOSPC = syscall.Errno(0x1c) + ENOSR = syscall.Errno(0x3f) + ENOSTR = syscall.Errno(0x3c) + ENOSYS = syscall.Errno(0x59) + ENOTBLK = syscall.Errno(0xf) + ENOTCONN = syscall.Errno(0x86) + ENOTDIR = syscall.Errno(0x14) + ENOTEMPTY = syscall.Errno(0x5d) + ENOTNAM = syscall.Errno(0x89) + ENOTRECOVERABLE = syscall.Errno(0xa6) + ENOTSOCK = syscall.Errno(0x5f) + ENOTSUP = syscall.Errno(0x7a) + ENOTTY = syscall.Errno(0x19) + ENOTUNIQ = syscall.Errno(0x50) + ENXIO = syscall.Errno(0x6) + EOPNOTSUPP = syscall.Errno(0x7a) + EOVERFLOW = syscall.Errno(0x4f) + EOWNERDEAD = syscall.Errno(0xa5) + EPERM = syscall.Errno(0x1) + EPFNOSUPPORT = syscall.Errno(0x7b) + EPIPE = syscall.Errno(0x20) + EPROTO = syscall.Errno(0x47) + EPROTONOSUPPORT = syscall.Errno(0x78) + EPROTOTYPE = syscall.Errno(0x62) + ERANGE = syscall.Errno(0x22) + EREMCHG = syscall.Errno(0x52) + EREMDEV = syscall.Errno(0x8e) + EREMOTE = syscall.Errno(0x42) + EREMOTEIO = syscall.Errno(0x8c) + ERESTART = syscall.Errno(0x5b) + ERFKILL = syscall.Errno(0xa7) + EROFS = syscall.Errno(0x1e) + ESHUTDOWN = syscall.Errno(0x8f) + ESOCKTNOSUPPORT = syscall.Errno(0x79) + ESPIPE = syscall.Errno(0x1d) + ESRCH = syscall.Errno(0x3) + ESRMNT = syscall.Errno(0x45) + ESTALE = syscall.Errno(0x97) + ESTRPIPE = syscall.Errno(0x5c) + ETIME = syscall.Errno(0x3e) + ETIMEDOUT = syscall.Errno(0x91) + ETOOMANYREFS = syscall.Errno(0x90) + ETXTBSY = syscall.Errno(0x1a) + EUCLEAN = syscall.Errno(0x87) + EUNATCH = syscall.Errno(0x2a) + EUSERS = syscall.Errno(0x5e) + EWOULDBLOCK = syscall.Errno(0xb) + EXDEV = syscall.Errno(0x12) + EXFULL = syscall.Errno(0x34) +) + +// Signals +const ( + SIGABRT = syscall.Signal(0x6) + SIGALRM = syscall.Signal(0xe) + SIGBUS = syscall.Signal(0xa) + SIGCHLD = syscall.Signal(0x12) + SIGCLD = syscall.Signal(0x12) + SIGCONT = syscall.Signal(0x19) + SIGEMT = syscall.Signal(0x7) + SIGFPE = syscall.Signal(0x8) + SIGHUP = syscall.Signal(0x1) + SIGILL = syscall.Signal(0x4) + SIGINT = syscall.Signal(0x2) + SIGIO = syscall.Signal(0x16) + SIGIOT = syscall.Signal(0x6) + SIGKILL = syscall.Signal(0x9) + SIGPIPE = syscall.Signal(0xd) + SIGPOLL = syscall.Signal(0x16) + SIGPROF = syscall.Signal(0x1d) + SIGPWR = syscall.Signal(0x13) + SIGQUIT = syscall.Signal(0x3) + SIGSEGV = syscall.Signal(0xb) + SIGSTOP = syscall.Signal(0x17) + SIGSYS = syscall.Signal(0xc) + SIGTERM = syscall.Signal(0xf) + SIGTRAP = syscall.Signal(0x5) + SIGTSTP = syscall.Signal(0x18) + SIGTTIN = syscall.Signal(0x1a) + SIGTTOU = syscall.Signal(0x1b) + SIGURG = syscall.Signal(0x15) + SIGUSR1 = syscall.Signal(0x10) + SIGUSR2 = syscall.Signal(0x11) + SIGVTALRM = syscall.Signal(0x1c) + SIGWINCH = syscall.Signal(0x14) + SIGXCPU = syscall.Signal(0x1e) + SIGXFSZ = syscall.Signal(0x1f) +) + +// Error table +var errors = [...]string{ + 1: "operation not permitted", + 2: "no such file or directory", + 3: "no such process", + 4: "interrupted system call", + 5: "input/output error", + 6: "no such device or address", + 7: "argument list too long", + 8: "exec format error", + 9: "bad file descriptor", + 10: "no child processes", + 11: "resource temporarily unavailable", + 12: "cannot allocate memory", + 13: "permission denied", + 14: "bad address", + 15: "block device required", + 16: "device or resource busy", + 17: "file exists", + 18: "invalid cross-device link", + 19: "no such device", + 20: "not a directory", + 21: "is a directory", + 22: "invalid argument", + 23: "too many open files in system", + 24: "too many open files", + 25: "inappropriate ioctl for device", + 26: "text file busy", + 27: "file too large", + 28: "no space left on device", + 29: "illegal seek", + 30: "read-only file system", + 31: "too many links", + 32: "broken pipe", + 33: "numerical argument out of domain", + 34: "numerical result out of range", + 35: "no message of desired type", + 36: "identifier removed", + 37: "channel number out of range", + 38: "level 2 not synchronized", + 39: "level 3 halted", + 40: "level 3 reset", + 41: "link number out of range", + 42: "protocol driver not attached", + 43: "no CSI structure available", + 44: "level 2 halted", + 45: "resource deadlock avoided", + 46: "no locks available", + 50: "invalid exchange", + 51: "invalid request descriptor", + 52: "exchange full", + 53: "no anode", + 54: "invalid request code", + 55: "invalid slot", + 56: "file locking deadlock error", + 59: "bad font file format", + 60: "device not a stream", + 61: "no data available", + 62: "timer expired", + 63: "out of streams resources", + 64: "machine is not on the network", + 65: "package not installed", + 66: "object is remote", + 67: "link has been severed", + 68: "advertise error", + 69: "srmount error", + 70: "communication error on send", + 71: "protocol error", + 73: "RFS specific error", + 74: "multihop attempted", + 77: "bad message", + 78: "file name too long", + 79: "value too large for defined data type", + 80: "name not unique on network", + 81: "file descriptor in bad state", + 82: "remote address changed", + 83: "can not access a needed shared library", + 84: "accessing a corrupted shared library", + 85: ".lib section in a.out corrupted", + 86: "attempting to link in too many shared libraries", + 87: "cannot exec a shared library directly", + 88: "invalid or incomplete multibyte or wide character", + 89: "function not implemented", + 90: "too many levels of symbolic links", + 91: "interrupted system call should be restarted", + 92: "streams pipe error", + 93: "directory not empty", + 94: "too many users", + 95: "socket operation on non-socket", + 96: "destination address required", + 97: "message too long", + 98: "protocol wrong type for socket", + 99: "protocol not available", + 120: "protocol not supported", + 121: "socket type not supported", + 122: "operation not supported", + 123: "protocol family not supported", + 124: "address family not supported by protocol", + 125: "address already in use", + 126: "cannot assign requested address", + 127: "network is down", + 128: "network is unreachable", + 129: "network dropped connection on reset", + 130: "software caused connection abort", + 131: "connection reset by peer", + 132: "no buffer space available", + 133: "transport endpoint is already connected", + 134: "transport endpoint is not connected", + 135: "structure needs cleaning", + 137: "not a XENIX named type file", + 138: "no XENIX semaphores available", + 139: "is a named type file", + 140: "remote I/O error", + 141: "unknown error 141", + 142: "unknown error 142", + 143: "cannot send after transport endpoint shutdown", + 144: "too many references: cannot splice", + 145: "connection timed out", + 146: "connection refused", + 147: "host is down", + 148: "no route to host", + 149: "operation already in progress", + 150: "operation now in progress", + 151: "stale NFS file handle", + 158: "operation canceled", + 159: "no medium found", + 160: "wrong medium type", + 161: "required key not available", + 162: "key has expired", + 163: "key has been revoked", + 164: "key was rejected by service", + 165: "owner died", + 166: "state not recoverable", + 167: "operation not possible due to RF-kill", + 168: "unknown error 168", + 1133: "disk quota exceeded", +} + +// Signal table +var signals = [...]string{ + 1: "hangup", + 2: "interrupt", + 3: "quit", + 4: "illegal instruction", + 5: "trace/breakpoint trap", + 6: "aborted", + 7: "EMT trap", + 8: "floating point exception", + 9: "killed", + 10: "bus error", + 11: "segmentation fault", + 12: "bad system call", + 13: "broken pipe", + 14: "alarm clock", + 15: "terminated", + 16: "user defined signal 1", + 17: "user defined signal 2", + 18: "child exited", + 19: "power failure", + 20: "window changed", + 21: "urgent I/O condition", + 22: "I/O possible", + 23: "stopped (signal)", + 24: "stopped", + 25: "continued", + 26: "stopped (tty input)", + 27: "stopped (tty output)", + 28: "virtual timer expired", + 29: "profiling timer expired", + 30: "CPU time limit exceeded", + 31: "file size limit exceeded", +} diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_mipsle.go b/vendor/golang.org/x/sys/unix/zerrors_linux_mipsle.go new file mode 100644 index 0000000..0f5ee22 --- /dev/null +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_mipsle.go @@ -0,0 +1,2020 @@ +// mkerrors.sh +// MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT + +// +build mipsle,linux + +// Created by cgo -godefs - DO NOT EDIT +// cgo -godefs -- _const.go + +package unix + +import "syscall" + +const ( + AF_ALG = 0x26 + AF_APPLETALK = 0x5 + AF_ASH = 0x12 + AF_ATMPVC = 0x8 + AF_ATMSVC = 0x14 + AF_AX25 = 0x3 + AF_BLUETOOTH = 0x1f + AF_BRIDGE = 0x7 + AF_CAIF = 0x25 + AF_CAN = 0x1d + AF_DECnet = 0xc + AF_ECONET = 0x13 + AF_FILE = 0x1 + AF_IB = 0x1b + AF_IEEE802154 = 0x24 + AF_INET = 0x2 + AF_INET6 = 0xa + AF_IPX = 0x4 + AF_IRDA = 0x17 + AF_ISDN = 0x22 + AF_IUCV = 0x20 + AF_KCM = 0x29 + AF_KEY = 0xf + AF_LLC = 0x1a + AF_LOCAL = 0x1 + AF_MAX = 0x2a + AF_MPLS = 0x1c + AF_NETBEUI = 0xd + AF_NETLINK = 0x10 + AF_NETROM = 0x6 + AF_NFC = 0x27 + AF_PACKET = 0x11 + AF_PHONET = 0x23 + AF_PPPOX = 0x18 + AF_RDS = 0x15 + AF_ROSE = 0xb + AF_ROUTE = 0x10 + AF_RXRPC = 0x21 + AF_SECURITY = 0xe + AF_SNA = 0x16 + AF_TIPC = 0x1e + AF_UNIX = 0x1 + AF_UNSPEC = 0x0 + AF_VSOCK = 0x28 + AF_WANPIPE = 0x19 + AF_X25 = 0x9 + ARPHRD_6LOWPAN = 0x339 + ARPHRD_ADAPT = 0x108 + ARPHRD_APPLETLK = 0x8 + ARPHRD_ARCNET = 0x7 + ARPHRD_ASH = 0x30d + ARPHRD_ATM = 0x13 + ARPHRD_AX25 = 0x3 + ARPHRD_BIF = 0x307 + ARPHRD_CAIF = 0x336 + ARPHRD_CAN = 0x118 + ARPHRD_CHAOS = 0x5 + ARPHRD_CISCO = 0x201 + ARPHRD_CSLIP = 0x101 + ARPHRD_CSLIP6 = 0x103 + ARPHRD_DDCMP = 0x205 + ARPHRD_DLCI = 0xf + ARPHRD_ECONET = 0x30e + ARPHRD_EETHER = 0x2 + ARPHRD_ETHER = 0x1 + ARPHRD_EUI64 = 0x1b + ARPHRD_FCAL = 0x311 + ARPHRD_FCFABRIC = 0x313 + ARPHRD_FCPL = 0x312 + ARPHRD_FCPP = 0x310 + ARPHRD_FDDI = 0x306 + ARPHRD_FRAD = 0x302 + ARPHRD_HDLC = 0x201 + ARPHRD_HIPPI = 0x30c + ARPHRD_HWX25 = 0x110 + ARPHRD_IEEE1394 = 0x18 + ARPHRD_IEEE802 = 0x6 + ARPHRD_IEEE80211 = 0x321 + ARPHRD_IEEE80211_PRISM = 0x322 + ARPHRD_IEEE80211_RADIOTAP = 0x323 + ARPHRD_IEEE802154 = 0x324 + ARPHRD_IEEE802154_MONITOR = 0x325 + ARPHRD_IEEE802_TR = 0x320 + ARPHRD_INFINIBAND = 0x20 + ARPHRD_IP6GRE = 0x337 + ARPHRD_IPDDP = 0x309 + ARPHRD_IPGRE = 0x30a + ARPHRD_IRDA = 0x30f + ARPHRD_LAPB = 0x204 + ARPHRD_LOCALTLK = 0x305 + ARPHRD_LOOPBACK = 0x304 + ARPHRD_METRICOM = 0x17 + ARPHRD_NETLINK = 0x338 + ARPHRD_NETROM = 0x0 + ARPHRD_NONE = 0xfffe + ARPHRD_PHONET = 0x334 + ARPHRD_PHONET_PIPE = 0x335 + ARPHRD_PIMREG = 0x30b + ARPHRD_PPP = 0x200 + ARPHRD_PRONET = 0x4 + ARPHRD_RAWHDLC = 0x206 + ARPHRD_ROSE = 0x10e + ARPHRD_RSRVD = 0x104 + ARPHRD_SIT = 0x308 + ARPHRD_SKIP = 0x303 + ARPHRD_SLIP = 0x100 + ARPHRD_SLIP6 = 0x102 + ARPHRD_TUNNEL = 0x300 + ARPHRD_TUNNEL6 = 0x301 + ARPHRD_VOID = 0xffff + ARPHRD_X25 = 0x10f + B0 = 0x0 + B1000000 = 0x1008 + B110 = 0x3 + B115200 = 0x1002 + B1152000 = 0x1009 + B1200 = 0x9 + B134 = 0x4 + B150 = 0x5 + B1500000 = 0x100a + B1800 = 0xa + B19200 = 0xe + B200 = 0x6 + B2000000 = 0x100b + B230400 = 0x1003 + B2400 = 0xb + B2500000 = 0x100c + B300 = 0x7 + B3000000 = 0x100d + B3500000 = 0x100e + B38400 = 0xf + B4000000 = 0x100f + B460800 = 0x1004 + B4800 = 0xc + B50 = 0x1 + B500000 = 0x1005 + B57600 = 0x1001 + B576000 = 0x1006 + B600 = 0x8 + B75 = 0x2 + B921600 = 0x1007 + B9600 = 0xd + BOTHER = 0x1000 + BPF_A = 0x10 + BPF_ABS = 0x20 + BPF_ADD = 0x0 + BPF_ALU = 0x4 + BPF_AND = 0x50 + BPF_B = 0x10 + BPF_DIV = 0x30 + BPF_H = 0x8 + BPF_IMM = 0x0 + BPF_IND = 0x40 + BPF_JA = 0x0 + BPF_JEQ = 0x10 + BPF_JGE = 0x30 + BPF_JGT = 0x20 + BPF_JMP = 0x5 + BPF_JSET = 0x40 + BPF_K = 0x0 + BPF_LD = 0x0 + BPF_LDX = 0x1 + BPF_LEN = 0x80 + BPF_LL_OFF = -0x200000 + BPF_LSH = 0x60 + BPF_MAJOR_VERSION = 0x1 + BPF_MAXINSNS = 0x1000 + BPF_MEM = 0x60 + BPF_MEMWORDS = 0x10 + BPF_MINOR_VERSION = 0x1 + BPF_MISC = 0x7 + BPF_MOD = 0x90 + BPF_MSH = 0xa0 + BPF_MUL = 0x20 + BPF_NEG = 0x80 + BPF_NET_OFF = -0x100000 + BPF_OR = 0x40 + BPF_RET = 0x6 + BPF_RSH = 0x70 + BPF_ST = 0x2 + BPF_STX = 0x3 + BPF_SUB = 0x10 + BPF_TAX = 0x0 + BPF_TXA = 0x80 + BPF_W = 0x0 + BPF_X = 0x8 + BPF_XOR = 0xa0 + BRKINT = 0x2 + BS0 = 0x0 + BS1 = 0x2000 + BSDLY = 0x2000 + CAN_BCM = 0x2 + CAN_EFF_FLAG = 0x80000000 + CAN_EFF_ID_BITS = 0x1d + CAN_EFF_MASK = 0x1fffffff + CAN_ERR_FLAG = 0x20000000 + CAN_ERR_MASK = 0x1fffffff + CAN_INV_FILTER = 0x20000000 + CAN_ISOTP = 0x6 + CAN_MAX_DLC = 0x8 + CAN_MAX_DLEN = 0x8 + CAN_MCNET = 0x5 + CAN_MTU = 0x10 + CAN_NPROTO = 0x7 + CAN_RAW = 0x1 + CAN_RTR_FLAG = 0x40000000 + CAN_SFF_ID_BITS = 0xb + CAN_SFF_MASK = 0x7ff + CAN_TP16 = 0x3 + CAN_TP20 = 0x4 + CBAUD = 0x100f + CBAUDEX = 0x1000 + CFLUSH = 0xf + CIBAUD = 0x100f0000 + CLOCAL = 0x800 + CLOCK_BOOTTIME = 0x7 + CLOCK_BOOTTIME_ALARM = 0x9 + CLOCK_DEFAULT = 0x0 + CLOCK_EXT = 0x1 + CLOCK_INT = 0x2 + CLOCK_MONOTONIC = 0x1 + CLOCK_MONOTONIC_COARSE = 0x6 + CLOCK_MONOTONIC_RAW = 0x4 + CLOCK_PROCESS_CPUTIME_ID = 0x2 + CLOCK_REALTIME = 0x0 + CLOCK_REALTIME_ALARM = 0x8 + CLOCK_REALTIME_COARSE = 0x5 + CLOCK_TAI = 0xb + CLOCK_THREAD_CPUTIME_ID = 0x3 + CLOCK_TXFROMRX = 0x4 + CLOCK_TXINT = 0x3 + CLONE_CHILD_CLEARTID = 0x200000 + CLONE_CHILD_SETTID = 0x1000000 + CLONE_DETACHED = 0x400000 + CLONE_FILES = 0x400 + CLONE_FS = 0x200 + CLONE_IO = 0x80000000 + CLONE_NEWCGROUP = 0x2000000 + CLONE_NEWIPC = 0x8000000 + CLONE_NEWNET = 0x40000000 + CLONE_NEWNS = 0x20000 + CLONE_NEWPID = 0x20000000 + CLONE_NEWUSER = 0x10000000 + CLONE_NEWUTS = 0x4000000 + CLONE_PARENT = 0x8000 + CLONE_PARENT_SETTID = 0x100000 + CLONE_PTRACE = 0x2000 + CLONE_SETTLS = 0x80000 + CLONE_SIGHAND = 0x800 + CLONE_SYSVSEM = 0x40000 + CLONE_THREAD = 0x10000 + CLONE_UNTRACED = 0x800000 + CLONE_VFORK = 0x4000 + CLONE_VM = 0x100 + CMSPAR = 0x40000000 + CR0 = 0x0 + CR1 = 0x200 + CR2 = 0x400 + CR3 = 0x600 + CRDLY = 0x600 + CREAD = 0x80 + CRTSCTS = 0x80000000 + CS5 = 0x0 + CS6 = 0x10 + CS7 = 0x20 + CS8 = 0x30 + CSIGNAL = 0xff + CSIZE = 0x30 + CSTART = 0x11 + CSTATUS = 0x0 + CSTOP = 0x13 + CSTOPB = 0x40 + CSUSP = 0x1a + DT_BLK = 0x6 + DT_CHR = 0x2 + DT_DIR = 0x4 + DT_FIFO = 0x1 + DT_LNK = 0xa + DT_REG = 0x8 + DT_SOCK = 0xc + DT_UNKNOWN = 0x0 + DT_WHT = 0xe + ECHO = 0x8 + ECHOCTL = 0x200 + ECHOE = 0x10 + ECHOK = 0x20 + ECHOKE = 0x800 + ECHONL = 0x40 + ECHOPRT = 0x400 + ENCODING_DEFAULT = 0x0 + ENCODING_FM_MARK = 0x3 + ENCODING_FM_SPACE = 0x4 + ENCODING_MANCHESTER = 0x5 + ENCODING_NRZ = 0x1 + ENCODING_NRZI = 0x2 + EPOLLERR = 0x8 + EPOLLET = 0x80000000 + EPOLLEXCLUSIVE = 0x10000000 + EPOLLHUP = 0x10 + EPOLLIN = 0x1 + EPOLLMSG = 0x400 + EPOLLONESHOT = 0x40000000 + EPOLLOUT = 0x4 + EPOLLPRI = 0x2 + EPOLLRDBAND = 0x80 + EPOLLRDHUP = 0x2000 + EPOLLRDNORM = 0x40 + EPOLLWAKEUP = 0x20000000 + EPOLLWRBAND = 0x200 + EPOLLWRNORM = 0x100 + EPOLL_CLOEXEC = 0x80000 + EPOLL_CTL_ADD = 0x1 + EPOLL_CTL_DEL = 0x2 + EPOLL_CTL_MOD = 0x3 + ETH_P_1588 = 0x88f7 + ETH_P_8021AD = 0x88a8 + ETH_P_8021AH = 0x88e7 + ETH_P_8021Q = 0x8100 + ETH_P_80221 = 0x8917 + ETH_P_802_2 = 0x4 + ETH_P_802_3 = 0x1 + ETH_P_802_3_MIN = 0x600 + ETH_P_802_EX1 = 0x88b5 + ETH_P_AARP = 0x80f3 + ETH_P_AF_IUCV = 0xfbfb + ETH_P_ALL = 0x3 + ETH_P_AOE = 0x88a2 + ETH_P_ARCNET = 0x1a + ETH_P_ARP = 0x806 + ETH_P_ATALK = 0x809b + ETH_P_ATMFATE = 0x8884 + ETH_P_ATMMPOA = 0x884c + ETH_P_AX25 = 0x2 + ETH_P_BATMAN = 0x4305 + ETH_P_BPQ = 0x8ff + ETH_P_CAIF = 0xf7 + ETH_P_CAN = 0xc + ETH_P_CANFD = 0xd + ETH_P_CONTROL = 0x16 + ETH_P_CUST = 0x6006 + ETH_P_DDCMP = 0x6 + ETH_P_DEC = 0x6000 + ETH_P_DIAG = 0x6005 + ETH_P_DNA_DL = 0x6001 + ETH_P_DNA_RC = 0x6002 + ETH_P_DNA_RT = 0x6003 + ETH_P_DSA = 0x1b + ETH_P_ECONET = 0x18 + ETH_P_EDSA = 0xdada + ETH_P_FCOE = 0x8906 + ETH_P_FIP = 0x8914 + ETH_P_HDLC = 0x19 + ETH_P_HSR = 0x892f + ETH_P_IEEE802154 = 0xf6 + ETH_P_IEEEPUP = 0xa00 + ETH_P_IEEEPUPAT = 0xa01 + ETH_P_IP = 0x800 + ETH_P_IPV6 = 0x86dd + ETH_P_IPX = 0x8137 + ETH_P_IRDA = 0x17 + ETH_P_LAT = 0x6004 + ETH_P_LINK_CTL = 0x886c + ETH_P_LOCALTALK = 0x9 + ETH_P_LOOP = 0x60 + ETH_P_LOOPBACK = 0x9000 + ETH_P_MACSEC = 0x88e5 + ETH_P_MOBITEX = 0x15 + ETH_P_MPLS_MC = 0x8848 + ETH_P_MPLS_UC = 0x8847 + ETH_P_MVRP = 0x88f5 + ETH_P_PAE = 0x888e + ETH_P_PAUSE = 0x8808 + ETH_P_PHONET = 0xf5 + ETH_P_PPPTALK = 0x10 + ETH_P_PPP_DISC = 0x8863 + ETH_P_PPP_MP = 0x8 + ETH_P_PPP_SES = 0x8864 + ETH_P_PRP = 0x88fb + ETH_P_PUP = 0x200 + ETH_P_PUPAT = 0x201 + ETH_P_QINQ1 = 0x9100 + ETH_P_QINQ2 = 0x9200 + ETH_P_QINQ3 = 0x9300 + ETH_P_RARP = 0x8035 + ETH_P_SCA = 0x6007 + ETH_P_SLOW = 0x8809 + ETH_P_SNAP = 0x5 + ETH_P_TDLS = 0x890d + ETH_P_TEB = 0x6558 + ETH_P_TIPC = 0x88ca + ETH_P_TRAILER = 0x1c + ETH_P_TR_802_2 = 0x11 + ETH_P_TSN = 0x22f0 + ETH_P_WAN_PPP = 0x7 + ETH_P_WCCP = 0x883e + ETH_P_X25 = 0x805 + ETH_P_XDSA = 0xf8 + EXTA = 0xe + EXTB = 0xf + EXTPROC = 0x10000 + FD_CLOEXEC = 0x1 + FD_SETSIZE = 0x400 + FF0 = 0x0 + FF1 = 0x8000 + FFDLY = 0x8000 + FLUSHO = 0x2000 + F_DUPFD = 0x0 + F_DUPFD_CLOEXEC = 0x406 + F_EXLCK = 0x4 + F_GETFD = 0x1 + F_GETFL = 0x3 + F_GETLEASE = 0x401 + F_GETLK = 0x21 + F_GETLK64 = 0x21 + F_GETOWN = 0x17 + F_GETOWN_EX = 0x10 + F_GETPIPE_SZ = 0x408 + F_GETSIG = 0xb + F_LOCK = 0x1 + F_NOTIFY = 0x402 + F_OFD_GETLK = 0x24 + F_OFD_SETLK = 0x25 + F_OFD_SETLKW = 0x26 + F_OK = 0x0 + F_RDLCK = 0x0 + F_SETFD = 0x2 + F_SETFL = 0x4 + F_SETLEASE = 0x400 + F_SETLK = 0x22 + F_SETLK64 = 0x22 + F_SETLKW = 0x23 + F_SETLKW64 = 0x23 + F_SETOWN = 0x18 + F_SETOWN_EX = 0xf + F_SETPIPE_SZ = 0x407 + F_SETSIG = 0xa + F_SHLCK = 0x8 + F_TEST = 0x3 + F_TLOCK = 0x2 + F_ULOCK = 0x0 + F_UNLCK = 0x2 + F_WRLCK = 0x1 + HUPCL = 0x400 + IBSHIFT = 0x10 + ICANON = 0x2 + ICMPV6_FILTER = 0x1 + ICRNL = 0x100 + IEXTEN = 0x100 + IFA_F_DADFAILED = 0x8 + IFA_F_DEPRECATED = 0x20 + IFA_F_HOMEADDRESS = 0x10 + IFA_F_MANAGETEMPADDR = 0x100 + IFA_F_MCAUTOJOIN = 0x400 + IFA_F_NODAD = 0x2 + IFA_F_NOPREFIXROUTE = 0x200 + IFA_F_OPTIMISTIC = 0x4 + IFA_F_PERMANENT = 0x80 + IFA_F_SECONDARY = 0x1 + IFA_F_STABLE_PRIVACY = 0x800 + IFA_F_TEMPORARY = 0x1 + IFA_F_TENTATIVE = 0x40 + IFA_MAX = 0x8 + IFF_ALLMULTI = 0x200 + IFF_ATTACH_QUEUE = 0x200 + IFF_AUTOMEDIA = 0x4000 + IFF_BROADCAST = 0x2 + IFF_DEBUG = 0x4 + IFF_DETACH_QUEUE = 0x400 + IFF_DORMANT = 0x20000 + IFF_DYNAMIC = 0x8000 + IFF_ECHO = 0x40000 + IFF_LOOPBACK = 0x8 + IFF_LOWER_UP = 0x10000 + IFF_MASTER = 0x400 + IFF_MULTICAST = 0x1000 + IFF_MULTI_QUEUE = 0x100 + IFF_NOARP = 0x80 + IFF_NOFILTER = 0x1000 + IFF_NOTRAILERS = 0x20 + IFF_NO_PI = 0x1000 + IFF_ONE_QUEUE = 0x2000 + IFF_PERSIST = 0x800 + IFF_POINTOPOINT = 0x10 + IFF_PORTSEL = 0x2000 + IFF_PROMISC = 0x100 + IFF_RUNNING = 0x40 + IFF_SLAVE = 0x800 + IFF_TAP = 0x2 + IFF_TUN = 0x1 + IFF_TUN_EXCL = 0x8000 + IFF_UP = 0x1 + IFF_VNET_HDR = 0x4000 + IFF_VOLATILE = 0x70c5a + IFNAMSIZ = 0x10 + IGNBRK = 0x1 + IGNCR = 0x80 + IGNPAR = 0x4 + IMAXBEL = 0x2000 + INLCR = 0x40 + INPCK = 0x10 + IN_ACCESS = 0x1 + IN_ALL_EVENTS = 0xfff + IN_ATTRIB = 0x4 + IN_CLASSA_HOST = 0xffffff + IN_CLASSA_MAX = 0x80 + IN_CLASSA_NET = 0xff000000 + IN_CLASSA_NSHIFT = 0x18 + IN_CLASSB_HOST = 0xffff + IN_CLASSB_MAX = 0x10000 + IN_CLASSB_NET = 0xffff0000 + IN_CLASSB_NSHIFT = 0x10 + IN_CLASSC_HOST = 0xff + IN_CLASSC_NET = 0xffffff00 + IN_CLASSC_NSHIFT = 0x8 + IN_CLOEXEC = 0x80000 + IN_CLOSE = 0x18 + IN_CLOSE_NOWRITE = 0x10 + IN_CLOSE_WRITE = 0x8 + IN_CREATE = 0x100 + IN_DELETE = 0x200 + IN_DELETE_SELF = 0x400 + IN_DONT_FOLLOW = 0x2000000 + IN_EXCL_UNLINK = 0x4000000 + IN_IGNORED = 0x8000 + IN_ISDIR = 0x40000000 + IN_LOOPBACKNET = 0x7f + IN_MASK_ADD = 0x20000000 + IN_MODIFY = 0x2 + IN_MOVE = 0xc0 + IN_MOVED_FROM = 0x40 + IN_MOVED_TO = 0x80 + IN_MOVE_SELF = 0x800 + IN_NONBLOCK = 0x80 + IN_ONESHOT = 0x80000000 + IN_ONLYDIR = 0x1000000 + IN_OPEN = 0x20 + IN_Q_OVERFLOW = 0x4000 + IN_UNMOUNT = 0x2000 + IPPROTO_AH = 0x33 + IPPROTO_BEETPH = 0x5e + IPPROTO_COMP = 0x6c + IPPROTO_DCCP = 0x21 + IPPROTO_DSTOPTS = 0x3c + IPPROTO_EGP = 0x8 + IPPROTO_ENCAP = 0x62 + IPPROTO_ESP = 0x32 + IPPROTO_FRAGMENT = 0x2c + IPPROTO_GRE = 0x2f + IPPROTO_HOPOPTS = 0x0 + IPPROTO_ICMP = 0x1 + IPPROTO_ICMPV6 = 0x3a + IPPROTO_IDP = 0x16 + IPPROTO_IGMP = 0x2 + IPPROTO_IP = 0x0 + IPPROTO_IPIP = 0x4 + IPPROTO_IPV6 = 0x29 + IPPROTO_MH = 0x87 + IPPROTO_MPLS = 0x89 + IPPROTO_MTP = 0x5c + IPPROTO_NONE = 0x3b + IPPROTO_PIM = 0x67 + IPPROTO_PUP = 0xc + IPPROTO_RAW = 0xff + IPPROTO_ROUTING = 0x2b + IPPROTO_RSVP = 0x2e + IPPROTO_SCTP = 0x84 + IPPROTO_TCP = 0x6 + IPPROTO_TP = 0x1d + IPPROTO_UDP = 0x11 + IPPROTO_UDPLITE = 0x88 + IPV6_2292DSTOPTS = 0x4 + IPV6_2292HOPLIMIT = 0x8 + IPV6_2292HOPOPTS = 0x3 + IPV6_2292PKTINFO = 0x2 + IPV6_2292PKTOPTIONS = 0x6 + IPV6_2292RTHDR = 0x5 + IPV6_ADDRFORM = 0x1 + IPV6_ADD_MEMBERSHIP = 0x14 + IPV6_AUTHHDR = 0xa + IPV6_CHECKSUM = 0x7 + IPV6_DONTFRAG = 0x3e + IPV6_DROP_MEMBERSHIP = 0x15 + IPV6_DSTOPTS = 0x3b + IPV6_HDRINCL = 0x24 + IPV6_HOPLIMIT = 0x34 + IPV6_HOPOPTS = 0x36 + IPV6_IPSEC_POLICY = 0x22 + IPV6_JOIN_ANYCAST = 0x1b + IPV6_JOIN_GROUP = 0x14 + IPV6_LEAVE_ANYCAST = 0x1c + IPV6_LEAVE_GROUP = 0x15 + IPV6_MTU = 0x18 + IPV6_MTU_DISCOVER = 0x17 + IPV6_MULTICAST_HOPS = 0x12 + IPV6_MULTICAST_IF = 0x11 + IPV6_MULTICAST_LOOP = 0x13 + IPV6_NEXTHOP = 0x9 + IPV6_PATHMTU = 0x3d + IPV6_PKTINFO = 0x32 + IPV6_PMTUDISC_DO = 0x2 + IPV6_PMTUDISC_DONT = 0x0 + IPV6_PMTUDISC_INTERFACE = 0x4 + IPV6_PMTUDISC_OMIT = 0x5 + IPV6_PMTUDISC_PROBE = 0x3 + IPV6_PMTUDISC_WANT = 0x1 + IPV6_RECVDSTOPTS = 0x3a + IPV6_RECVERR = 0x19 + IPV6_RECVHOPLIMIT = 0x33 + IPV6_RECVHOPOPTS = 0x35 + IPV6_RECVPATHMTU = 0x3c + IPV6_RECVPKTINFO = 0x31 + IPV6_RECVRTHDR = 0x38 + IPV6_RECVTCLASS = 0x42 + IPV6_ROUTER_ALERT = 0x16 + IPV6_RTHDR = 0x39 + IPV6_RTHDRDSTOPTS = 0x37 + IPV6_RTHDR_LOOSE = 0x0 + IPV6_RTHDR_STRICT = 0x1 + IPV6_RTHDR_TYPE_0 = 0x0 + IPV6_RXDSTOPTS = 0x3b + IPV6_RXHOPOPTS = 0x36 + IPV6_TCLASS = 0x43 + IPV6_UNICAST_HOPS = 0x10 + IPV6_V6ONLY = 0x1a + IPV6_XFRM_POLICY = 0x23 + IP_ADD_MEMBERSHIP = 0x23 + IP_ADD_SOURCE_MEMBERSHIP = 0x27 + IP_BIND_ADDRESS_NO_PORT = 0x18 + IP_BLOCK_SOURCE = 0x26 + IP_CHECKSUM = 0x17 + IP_DEFAULT_MULTICAST_LOOP = 0x1 + IP_DEFAULT_MULTICAST_TTL = 0x1 + IP_DF = 0x4000 + IP_DROP_MEMBERSHIP = 0x24 + IP_DROP_SOURCE_MEMBERSHIP = 0x28 + IP_FREEBIND = 0xf + IP_HDRINCL = 0x3 + IP_IPSEC_POLICY = 0x10 + IP_MAXPACKET = 0xffff + IP_MAX_MEMBERSHIPS = 0x14 + IP_MF = 0x2000 + IP_MINTTL = 0x15 + IP_MSFILTER = 0x29 + IP_MSS = 0x240 + IP_MTU = 0xe + IP_MTU_DISCOVER = 0xa + IP_MULTICAST_ALL = 0x31 + IP_MULTICAST_IF = 0x20 + IP_MULTICAST_LOOP = 0x22 + IP_MULTICAST_TTL = 0x21 + IP_NODEFRAG = 0x16 + IP_OFFMASK = 0x1fff + IP_OPTIONS = 0x4 + IP_ORIGDSTADDR = 0x14 + IP_PASSSEC = 0x12 + IP_PKTINFO = 0x8 + IP_PKTOPTIONS = 0x9 + IP_PMTUDISC = 0xa + IP_PMTUDISC_DO = 0x2 + IP_PMTUDISC_DONT = 0x0 + IP_PMTUDISC_INTERFACE = 0x4 + IP_PMTUDISC_OMIT = 0x5 + IP_PMTUDISC_PROBE = 0x3 + IP_PMTUDISC_WANT = 0x1 + IP_RECVERR = 0xb + IP_RECVOPTS = 0x6 + IP_RECVORIGDSTADDR = 0x14 + IP_RECVRETOPTS = 0x7 + IP_RECVTOS = 0xd + IP_RECVTTL = 0xc + IP_RETOPTS = 0x7 + IP_RF = 0x8000 + IP_ROUTER_ALERT = 0x5 + IP_TOS = 0x1 + IP_TRANSPARENT = 0x13 + IP_TTL = 0x2 + IP_UNBLOCK_SOURCE = 0x25 + IP_UNICAST_IF = 0x32 + IP_XFRM_POLICY = 0x11 + ISIG = 0x1 + ISTRIP = 0x20 + IUCLC = 0x200 + IUTF8 = 0x4000 + IXANY = 0x800 + IXOFF = 0x1000 + IXON = 0x400 + LINUX_REBOOT_CMD_CAD_OFF = 0x0 + LINUX_REBOOT_CMD_CAD_ON = 0x89abcdef + LINUX_REBOOT_CMD_HALT = 0xcdef0123 + LINUX_REBOOT_CMD_KEXEC = 0x45584543 + LINUX_REBOOT_CMD_POWER_OFF = 0x4321fedc + LINUX_REBOOT_CMD_RESTART = 0x1234567 + LINUX_REBOOT_CMD_RESTART2 = 0xa1b2c3d4 + LINUX_REBOOT_CMD_SW_SUSPEND = 0xd000fce2 + LINUX_REBOOT_MAGIC1 = 0xfee1dead + LINUX_REBOOT_MAGIC2 = 0x28121969 + LOCK_EX = 0x2 + LOCK_NB = 0x4 + LOCK_SH = 0x1 + LOCK_UN = 0x8 + MADV_DODUMP = 0x11 + MADV_DOFORK = 0xb + MADV_DONTDUMP = 0x10 + MADV_DONTFORK = 0xa + MADV_DONTNEED = 0x4 + MADV_FREE = 0x8 + MADV_HUGEPAGE = 0xe + MADV_HWPOISON = 0x64 + MADV_MERGEABLE = 0xc + MADV_NOHUGEPAGE = 0xf + MADV_NORMAL = 0x0 + MADV_RANDOM = 0x1 + MADV_REMOVE = 0x9 + MADV_SEQUENTIAL = 0x2 + MADV_UNMERGEABLE = 0xd + MADV_WILLNEED = 0x3 + MAP_ANON = 0x800 + MAP_ANONYMOUS = 0x800 + MAP_DENYWRITE = 0x2000 + MAP_EXECUTABLE = 0x4000 + MAP_FILE = 0x0 + MAP_FIXED = 0x10 + MAP_GROWSDOWN = 0x1000 + MAP_HUGETLB = 0x80000 + MAP_HUGE_MASK = 0x3f + MAP_HUGE_SHIFT = 0x1a + MAP_LOCKED = 0x8000 + MAP_NONBLOCK = 0x20000 + MAP_NORESERVE = 0x400 + MAP_POPULATE = 0x10000 + MAP_PRIVATE = 0x2 + MAP_RENAME = 0x800 + MAP_SHARED = 0x1 + MAP_STACK = 0x40000 + MAP_TYPE = 0xf + MCL_CURRENT = 0x1 + MCL_FUTURE = 0x2 + MCL_ONFAULT = 0x4 + MNT_DETACH = 0x2 + MNT_EXPIRE = 0x4 + MNT_FORCE = 0x1 + MSG_BATCH = 0x40000 + MSG_CMSG_CLOEXEC = 0x40000000 + MSG_CONFIRM = 0x800 + MSG_CTRUNC = 0x8 + MSG_DONTROUTE = 0x4 + MSG_DONTWAIT = 0x40 + MSG_EOR = 0x80 + MSG_ERRQUEUE = 0x2000 + MSG_FASTOPEN = 0x20000000 + MSG_FIN = 0x200 + MSG_MORE = 0x8000 + MSG_NOSIGNAL = 0x4000 + MSG_OOB = 0x1 + MSG_PEEK = 0x2 + MSG_PROXY = 0x10 + MSG_RST = 0x1000 + MSG_SYN = 0x400 + MSG_TRUNC = 0x20 + MSG_TRYHARD = 0x4 + MSG_WAITALL = 0x100 + MSG_WAITFORONE = 0x10000 + MS_ACTIVE = 0x40000000 + MS_ASYNC = 0x1 + MS_BIND = 0x1000 + MS_DIRSYNC = 0x80 + MS_INVALIDATE = 0x2 + MS_I_VERSION = 0x800000 + MS_KERNMOUNT = 0x400000 + MS_LAZYTIME = 0x2000000 + MS_MANDLOCK = 0x40 + MS_MGC_MSK = 0xffff0000 + MS_MGC_VAL = 0xc0ed0000 + MS_MOVE = 0x2000 + MS_NOATIME = 0x400 + MS_NODEV = 0x4 + MS_NODIRATIME = 0x800 + MS_NOEXEC = 0x8 + MS_NOSUID = 0x2 + MS_NOUSER = -0x80000000 + MS_POSIXACL = 0x10000 + MS_PRIVATE = 0x40000 + MS_RDONLY = 0x1 + MS_REC = 0x4000 + MS_RELATIME = 0x200000 + MS_REMOUNT = 0x20 + MS_RMT_MASK = 0x2800051 + MS_SHARED = 0x100000 + MS_SILENT = 0x8000 + MS_SLAVE = 0x80000 + MS_STRICTATIME = 0x1000000 + MS_SYNC = 0x4 + MS_SYNCHRONOUS = 0x10 + MS_UNBINDABLE = 0x20000 + NAME_MAX = 0xff + NETLINK_ADD_MEMBERSHIP = 0x1 + NETLINK_AUDIT = 0x9 + NETLINK_BROADCAST_ERROR = 0x4 + NETLINK_CAP_ACK = 0xa + NETLINK_CONNECTOR = 0xb + NETLINK_CRYPTO = 0x15 + NETLINK_DNRTMSG = 0xe + NETLINK_DROP_MEMBERSHIP = 0x2 + NETLINK_ECRYPTFS = 0x13 + NETLINK_FIB_LOOKUP = 0xa + NETLINK_FIREWALL = 0x3 + NETLINK_GENERIC = 0x10 + NETLINK_INET_DIAG = 0x4 + NETLINK_IP6_FW = 0xd + NETLINK_ISCSI = 0x8 + NETLINK_KOBJECT_UEVENT = 0xf + NETLINK_LISTEN_ALL_NSID = 0x8 + NETLINK_LIST_MEMBERSHIPS = 0x9 + NETLINK_NETFILTER = 0xc + NETLINK_NFLOG = 0x5 + NETLINK_NO_ENOBUFS = 0x5 + NETLINK_PKTINFO = 0x3 + NETLINK_RDMA = 0x14 + NETLINK_ROUTE = 0x0 + NETLINK_RX_RING = 0x6 + NETLINK_SCSITRANSPORT = 0x12 + NETLINK_SELINUX = 0x7 + NETLINK_SOCK_DIAG = 0x4 + NETLINK_TX_RING = 0x7 + NETLINK_UNUSED = 0x1 + NETLINK_USERSOCK = 0x2 + NETLINK_XFRM = 0x6 + NL0 = 0x0 + NL1 = 0x100 + NLA_ALIGNTO = 0x4 + NLA_F_NESTED = 0x8000 + NLA_F_NET_BYTEORDER = 0x4000 + NLA_HDRLEN = 0x4 + NLDLY = 0x100 + NLMSG_ALIGNTO = 0x4 + NLMSG_DONE = 0x3 + NLMSG_ERROR = 0x2 + NLMSG_HDRLEN = 0x10 + NLMSG_MIN_TYPE = 0x10 + NLMSG_NOOP = 0x1 + NLMSG_OVERRUN = 0x4 + NLM_F_ACK = 0x4 + NLM_F_APPEND = 0x800 + NLM_F_ATOMIC = 0x400 + NLM_F_CREATE = 0x400 + NLM_F_DUMP = 0x300 + NLM_F_DUMP_FILTERED = 0x20 + NLM_F_DUMP_INTR = 0x10 + NLM_F_ECHO = 0x8 + NLM_F_EXCL = 0x200 + NLM_F_MATCH = 0x200 + NLM_F_MULTI = 0x2 + NLM_F_REPLACE = 0x100 + NLM_F_REQUEST = 0x1 + NLM_F_ROOT = 0x100 + NOFLSH = 0x80 + OCRNL = 0x8 + OFDEL = 0x80 + OFILL = 0x40 + OLCUC = 0x2 + ONLCR = 0x4 + ONLRET = 0x20 + ONOCR = 0x10 + OPOST = 0x1 + O_ACCMODE = 0x3 + O_APPEND = 0x8 + O_ASYNC = 0x1000 + O_CLOEXEC = 0x80000 + O_CREAT = 0x100 + O_DIRECT = 0x8000 + O_DIRECTORY = 0x10000 + O_DSYNC = 0x10 + O_EXCL = 0x400 + O_FSYNC = 0x4010 + O_LARGEFILE = 0x2000 + O_NDELAY = 0x80 + O_NOATIME = 0x40000 + O_NOCTTY = 0x800 + O_NOFOLLOW = 0x20000 + O_NONBLOCK = 0x80 + O_PATH = 0x200000 + O_RDONLY = 0x0 + O_RDWR = 0x2 + O_RSYNC = 0x4010 + O_SYNC = 0x4010 + O_TMPFILE = 0x410000 + O_TRUNC = 0x200 + O_WRONLY = 0x1 + PACKET_ADD_MEMBERSHIP = 0x1 + PACKET_AUXDATA = 0x8 + PACKET_BROADCAST = 0x1 + PACKET_COPY_THRESH = 0x7 + PACKET_DROP_MEMBERSHIP = 0x2 + PACKET_FANOUT = 0x12 + PACKET_FANOUT_CBPF = 0x6 + PACKET_FANOUT_CPU = 0x2 + PACKET_FANOUT_DATA = 0x16 + PACKET_FANOUT_EBPF = 0x7 + PACKET_FANOUT_FLAG_DEFRAG = 0x8000 + PACKET_FANOUT_FLAG_ROLLOVER = 0x1000 + PACKET_FANOUT_HASH = 0x0 + PACKET_FANOUT_LB = 0x1 + PACKET_FANOUT_QM = 0x5 + PACKET_FANOUT_RND = 0x4 + PACKET_FANOUT_ROLLOVER = 0x3 + PACKET_FASTROUTE = 0x6 + PACKET_HDRLEN = 0xb + PACKET_HOST = 0x0 + PACKET_KERNEL = 0x7 + PACKET_LOOPBACK = 0x5 + PACKET_LOSS = 0xe + PACKET_MR_ALLMULTI = 0x2 + PACKET_MR_MULTICAST = 0x0 + PACKET_MR_PROMISC = 0x1 + PACKET_MR_UNICAST = 0x3 + PACKET_MULTICAST = 0x2 + PACKET_ORIGDEV = 0x9 + PACKET_OTHERHOST = 0x3 + PACKET_OUTGOING = 0x4 + PACKET_QDISC_BYPASS = 0x14 + PACKET_RECV_OUTPUT = 0x3 + PACKET_RESERVE = 0xc + PACKET_ROLLOVER_STATS = 0x15 + PACKET_RX_RING = 0x5 + PACKET_STATISTICS = 0x6 + PACKET_TIMESTAMP = 0x11 + PACKET_TX_HAS_OFF = 0x13 + PACKET_TX_RING = 0xd + PACKET_TX_TIMESTAMP = 0x10 + PACKET_USER = 0x6 + PACKET_VERSION = 0xa + PACKET_VNET_HDR = 0xf + PARENB = 0x100 + PARITY_CRC16_PR0 = 0x2 + PARITY_CRC16_PR0_CCITT = 0x4 + PARITY_CRC16_PR1 = 0x3 + PARITY_CRC16_PR1_CCITT = 0x5 + PARITY_CRC32_PR0_CCITT = 0x6 + PARITY_CRC32_PR1_CCITT = 0x7 + PARITY_DEFAULT = 0x0 + PARITY_NONE = 0x1 + PARMRK = 0x8 + PARODD = 0x200 + PENDIN = 0x4000 + PRIO_PGRP = 0x1 + PRIO_PROCESS = 0x0 + PRIO_USER = 0x2 + PROT_EXEC = 0x4 + PROT_GROWSDOWN = 0x1000000 + PROT_GROWSUP = 0x2000000 + PROT_NONE = 0x0 + PROT_READ = 0x1 + PROT_WRITE = 0x2 + PR_CAPBSET_DROP = 0x18 + PR_CAPBSET_READ = 0x17 + PR_CAP_AMBIENT = 0x2f + PR_CAP_AMBIENT_CLEAR_ALL = 0x4 + PR_CAP_AMBIENT_IS_SET = 0x1 + PR_CAP_AMBIENT_LOWER = 0x3 + PR_CAP_AMBIENT_RAISE = 0x2 + PR_ENDIAN_BIG = 0x0 + PR_ENDIAN_LITTLE = 0x1 + PR_ENDIAN_PPC_LITTLE = 0x2 + PR_FPEMU_NOPRINT = 0x1 + PR_FPEMU_SIGFPE = 0x2 + PR_FP_EXC_ASYNC = 0x2 + PR_FP_EXC_DISABLED = 0x0 + PR_FP_EXC_DIV = 0x10000 + PR_FP_EXC_INV = 0x100000 + PR_FP_EXC_NONRECOV = 0x1 + PR_FP_EXC_OVF = 0x20000 + PR_FP_EXC_PRECISE = 0x3 + PR_FP_EXC_RES = 0x80000 + PR_FP_EXC_SW_ENABLE = 0x80 + PR_FP_EXC_UND = 0x40000 + PR_FP_MODE_FR = 0x1 + PR_FP_MODE_FRE = 0x2 + PR_GET_CHILD_SUBREAPER = 0x25 + PR_GET_DUMPABLE = 0x3 + PR_GET_ENDIAN = 0x13 + PR_GET_FPEMU = 0x9 + PR_GET_FPEXC = 0xb + PR_GET_FP_MODE = 0x2e + PR_GET_KEEPCAPS = 0x7 + PR_GET_NAME = 0x10 + PR_GET_NO_NEW_PRIVS = 0x27 + PR_GET_PDEATHSIG = 0x2 + PR_GET_SECCOMP = 0x15 + PR_GET_SECUREBITS = 0x1b + PR_GET_THP_DISABLE = 0x2a + PR_GET_TID_ADDRESS = 0x28 + PR_GET_TIMERSLACK = 0x1e + PR_GET_TIMING = 0xd + PR_GET_TSC = 0x19 + PR_GET_UNALIGN = 0x5 + PR_MCE_KILL = 0x21 + PR_MCE_KILL_CLEAR = 0x0 + PR_MCE_KILL_DEFAULT = 0x2 + PR_MCE_KILL_EARLY = 0x1 + PR_MCE_KILL_GET = 0x22 + PR_MCE_KILL_LATE = 0x0 + PR_MCE_KILL_SET = 0x1 + PR_MPX_DISABLE_MANAGEMENT = 0x2c + PR_MPX_ENABLE_MANAGEMENT = 0x2b + PR_SET_CHILD_SUBREAPER = 0x24 + PR_SET_DUMPABLE = 0x4 + PR_SET_ENDIAN = 0x14 + PR_SET_FPEMU = 0xa + PR_SET_FPEXC = 0xc + PR_SET_FP_MODE = 0x2d + PR_SET_KEEPCAPS = 0x8 + PR_SET_MM = 0x23 + PR_SET_MM_ARG_END = 0x9 + PR_SET_MM_ARG_START = 0x8 + PR_SET_MM_AUXV = 0xc + PR_SET_MM_BRK = 0x7 + PR_SET_MM_END_CODE = 0x2 + PR_SET_MM_END_DATA = 0x4 + PR_SET_MM_ENV_END = 0xb + PR_SET_MM_ENV_START = 0xa + PR_SET_MM_EXE_FILE = 0xd + PR_SET_MM_MAP = 0xe + PR_SET_MM_MAP_SIZE = 0xf + PR_SET_MM_START_BRK = 0x6 + PR_SET_MM_START_CODE = 0x1 + PR_SET_MM_START_DATA = 0x3 + PR_SET_MM_START_STACK = 0x5 + PR_SET_NAME = 0xf + PR_SET_NO_NEW_PRIVS = 0x26 + PR_SET_PDEATHSIG = 0x1 + PR_SET_PTRACER = 0x59616d61 + PR_SET_PTRACER_ANY = 0xffffffff + PR_SET_SECCOMP = 0x16 + PR_SET_SECUREBITS = 0x1c + PR_SET_THP_DISABLE = 0x29 + PR_SET_TIMERSLACK = 0x1d + PR_SET_TIMING = 0xe + PR_SET_TSC = 0x1a + PR_SET_UNALIGN = 0x6 + PR_TASK_PERF_EVENTS_DISABLE = 0x1f + PR_TASK_PERF_EVENTS_ENABLE = 0x20 + PR_TIMING_STATISTICAL = 0x0 + PR_TIMING_TIMESTAMP = 0x1 + PR_TSC_ENABLE = 0x1 + PR_TSC_SIGSEGV = 0x2 + PR_UNALIGN_NOPRINT = 0x1 + PR_UNALIGN_SIGBUS = 0x2 + PTRACE_ATTACH = 0x10 + PTRACE_CONT = 0x7 + PTRACE_DETACH = 0x11 + PTRACE_EVENT_CLONE = 0x3 + PTRACE_EVENT_EXEC = 0x4 + PTRACE_EVENT_EXIT = 0x6 + PTRACE_EVENT_FORK = 0x1 + PTRACE_EVENT_SECCOMP = 0x7 + PTRACE_EVENT_STOP = 0x80 + PTRACE_EVENT_VFORK = 0x2 + PTRACE_EVENT_VFORK_DONE = 0x5 + PTRACE_GETEVENTMSG = 0x4201 + PTRACE_GETFPREGS = 0xe + PTRACE_GETREGS = 0xc + PTRACE_GETREGSET = 0x4204 + PTRACE_GETSIGINFO = 0x4202 + PTRACE_GETSIGMASK = 0x420a + PTRACE_GET_THREAD_AREA = 0x19 + PTRACE_GET_THREAD_AREA_3264 = 0xc4 + PTRACE_GET_WATCH_REGS = 0xd0 + PTRACE_INTERRUPT = 0x4207 + PTRACE_KILL = 0x8 + PTRACE_LISTEN = 0x4208 + PTRACE_OLDSETOPTIONS = 0x15 + PTRACE_O_EXITKILL = 0x100000 + PTRACE_O_MASK = 0x3000ff + PTRACE_O_SUSPEND_SECCOMP = 0x200000 + PTRACE_O_TRACECLONE = 0x8 + PTRACE_O_TRACEEXEC = 0x10 + PTRACE_O_TRACEEXIT = 0x40 + PTRACE_O_TRACEFORK = 0x2 + PTRACE_O_TRACESECCOMP = 0x80 + PTRACE_O_TRACESYSGOOD = 0x1 + PTRACE_O_TRACEVFORK = 0x4 + PTRACE_O_TRACEVFORKDONE = 0x20 + PTRACE_PEEKDATA = 0x2 + PTRACE_PEEKDATA_3264 = 0xc1 + PTRACE_PEEKSIGINFO = 0x4209 + PTRACE_PEEKSIGINFO_SHARED = 0x1 + PTRACE_PEEKTEXT = 0x1 + PTRACE_PEEKTEXT_3264 = 0xc0 + PTRACE_PEEKUSR = 0x3 + PTRACE_POKEDATA = 0x5 + PTRACE_POKEDATA_3264 = 0xc3 + PTRACE_POKETEXT = 0x4 + PTRACE_POKETEXT_3264 = 0xc2 + PTRACE_POKEUSR = 0x6 + PTRACE_SECCOMP_GET_FILTER = 0x420c + PTRACE_SEIZE = 0x4206 + PTRACE_SETFPREGS = 0xf + PTRACE_SETOPTIONS = 0x4200 + PTRACE_SETREGS = 0xd + PTRACE_SETREGSET = 0x4205 + PTRACE_SETSIGINFO = 0x4203 + PTRACE_SETSIGMASK = 0x420b + PTRACE_SET_THREAD_AREA = 0x1a + PTRACE_SET_WATCH_REGS = 0xd1 + PTRACE_SINGLESTEP = 0x9 + PTRACE_SYSCALL = 0x18 + PTRACE_TRACEME = 0x0 + RLIMIT_AS = 0x6 + RLIMIT_CORE = 0x4 + RLIMIT_CPU = 0x0 + RLIMIT_DATA = 0x2 + RLIMIT_FSIZE = 0x1 + RLIMIT_NOFILE = 0x5 + RLIMIT_STACK = 0x3 + RLIM_INFINITY = -0x1 + RTAX_ADVMSS = 0x8 + RTAX_CC_ALGO = 0x10 + RTAX_CWND = 0x7 + RTAX_FEATURES = 0xc + RTAX_FEATURE_ALLFRAG = 0x8 + RTAX_FEATURE_ECN = 0x1 + RTAX_FEATURE_MASK = 0xf + RTAX_FEATURE_SACK = 0x2 + RTAX_FEATURE_TIMESTAMP = 0x4 + RTAX_HOPLIMIT = 0xa + RTAX_INITCWND = 0xb + RTAX_INITRWND = 0xe + RTAX_LOCK = 0x1 + RTAX_MAX = 0x10 + RTAX_MTU = 0x2 + RTAX_QUICKACK = 0xf + RTAX_REORDERING = 0x9 + RTAX_RTO_MIN = 0xd + RTAX_RTT = 0x4 + RTAX_RTTVAR = 0x5 + RTAX_SSTHRESH = 0x6 + RTAX_UNSPEC = 0x0 + RTAX_WINDOW = 0x3 + RTA_ALIGNTO = 0x4 + RTA_MAX = 0x18 + RTCF_DIRECTSRC = 0x4000000 + RTCF_DOREDIRECT = 0x1000000 + RTCF_LOG = 0x2000000 + RTCF_MASQ = 0x400000 + RTCF_NAT = 0x800000 + RTCF_VALVE = 0x200000 + RTF_ADDRCLASSMASK = 0xf8000000 + RTF_ADDRCONF = 0x40000 + RTF_ALLONLINK = 0x20000 + RTF_BROADCAST = 0x10000000 + RTF_CACHE = 0x1000000 + RTF_DEFAULT = 0x10000 + RTF_DYNAMIC = 0x10 + RTF_FLOW = 0x2000000 + RTF_GATEWAY = 0x2 + RTF_HOST = 0x4 + RTF_INTERFACE = 0x40000000 + RTF_IRTT = 0x100 + RTF_LINKRT = 0x100000 + RTF_LOCAL = 0x80000000 + RTF_MODIFIED = 0x20 + RTF_MSS = 0x40 + RTF_MTU = 0x40 + RTF_MULTICAST = 0x20000000 + RTF_NAT = 0x8000000 + RTF_NOFORWARD = 0x1000 + RTF_NONEXTHOP = 0x200000 + RTF_NOPMTUDISC = 0x4000 + RTF_POLICY = 0x4000000 + RTF_REINSTATE = 0x8 + RTF_REJECT = 0x200 + RTF_STATIC = 0x400 + RTF_THROW = 0x2000 + RTF_UP = 0x1 + RTF_WINDOW = 0x80 + RTF_XRESOLVE = 0x800 + RTM_BASE = 0x10 + RTM_DELACTION = 0x31 + RTM_DELADDR = 0x15 + RTM_DELADDRLABEL = 0x49 + RTM_DELLINK = 0x11 + RTM_DELMDB = 0x55 + RTM_DELNEIGH = 0x1d + RTM_DELNSID = 0x59 + RTM_DELQDISC = 0x25 + RTM_DELROUTE = 0x19 + RTM_DELRULE = 0x21 + RTM_DELTCLASS = 0x29 + RTM_DELTFILTER = 0x2d + RTM_F_CLONED = 0x200 + RTM_F_EQUALIZE = 0x400 + RTM_F_LOOKUP_TABLE = 0x1000 + RTM_F_NOTIFY = 0x100 + RTM_F_PREFIX = 0x800 + RTM_GETACTION = 0x32 + RTM_GETADDR = 0x16 + RTM_GETADDRLABEL = 0x4a + RTM_GETANYCAST = 0x3e + RTM_GETDCB = 0x4e + RTM_GETLINK = 0x12 + RTM_GETMDB = 0x56 + RTM_GETMULTICAST = 0x3a + RTM_GETNEIGH = 0x1e + RTM_GETNEIGHTBL = 0x42 + RTM_GETNETCONF = 0x52 + RTM_GETNSID = 0x5a + RTM_GETQDISC = 0x26 + RTM_GETROUTE = 0x1a + RTM_GETRULE = 0x22 + RTM_GETSTATS = 0x5e + RTM_GETTCLASS = 0x2a + RTM_GETTFILTER = 0x2e + RTM_MAX = 0x5f + RTM_NEWACTION = 0x30 + RTM_NEWADDR = 0x14 + RTM_NEWADDRLABEL = 0x48 + RTM_NEWLINK = 0x10 + RTM_NEWMDB = 0x54 + RTM_NEWNDUSEROPT = 0x44 + RTM_NEWNEIGH = 0x1c + RTM_NEWNEIGHTBL = 0x40 + RTM_NEWNETCONF = 0x50 + RTM_NEWNSID = 0x58 + RTM_NEWPREFIX = 0x34 + RTM_NEWQDISC = 0x24 + RTM_NEWROUTE = 0x18 + RTM_NEWRULE = 0x20 + RTM_NEWSTATS = 0x5c + RTM_NEWTCLASS = 0x28 + RTM_NEWTFILTER = 0x2c + RTM_NR_FAMILIES = 0x14 + RTM_NR_MSGTYPES = 0x50 + RTM_SETDCB = 0x4f + RTM_SETLINK = 0x13 + RTM_SETNEIGHTBL = 0x43 + RTNH_ALIGNTO = 0x4 + RTNH_COMPARE_MASK = 0x11 + RTNH_F_DEAD = 0x1 + RTNH_F_LINKDOWN = 0x10 + RTNH_F_OFFLOAD = 0x8 + RTNH_F_ONLINK = 0x4 + RTNH_F_PERVASIVE = 0x2 + RTN_MAX = 0xb + RTPROT_BABEL = 0x2a + RTPROT_BIRD = 0xc + RTPROT_BOOT = 0x3 + RTPROT_DHCP = 0x10 + RTPROT_DNROUTED = 0xd + RTPROT_GATED = 0x8 + RTPROT_KERNEL = 0x2 + RTPROT_MROUTED = 0x11 + RTPROT_MRT = 0xa + RTPROT_NTK = 0xf + RTPROT_RA = 0x9 + RTPROT_REDIRECT = 0x1 + RTPROT_STATIC = 0x4 + RTPROT_UNSPEC = 0x0 + RTPROT_XORP = 0xe + RTPROT_ZEBRA = 0xb + RT_CLASS_DEFAULT = 0xfd + RT_CLASS_LOCAL = 0xff + RT_CLASS_MAIN = 0xfe + RT_CLASS_MAX = 0xff + RT_CLASS_UNSPEC = 0x0 + RUSAGE_CHILDREN = -0x1 + RUSAGE_SELF = 0x0 + RUSAGE_THREAD = 0x1 + SCM_CREDENTIALS = 0x2 + SCM_RIGHTS = 0x1 + SCM_TIMESTAMP = 0x1d + SCM_TIMESTAMPING = 0x25 + SCM_TIMESTAMPNS = 0x23 + SCM_WIFI_STATUS = 0x29 + SHUT_RD = 0x0 + SHUT_RDWR = 0x2 + SHUT_WR = 0x1 + SIOCADDDLCI = 0x8980 + SIOCADDMULTI = 0x8931 + SIOCADDRT = 0x890b + SIOCATMARK = 0x40047307 + SIOCDARP = 0x8953 + SIOCDELDLCI = 0x8981 + SIOCDELMULTI = 0x8932 + SIOCDELRT = 0x890c + SIOCDEVPRIVATE = 0x89f0 + SIOCDIFADDR = 0x8936 + SIOCDRARP = 0x8960 + SIOCGARP = 0x8954 + SIOCGIFADDR = 0x8915 + SIOCGIFBR = 0x8940 + SIOCGIFBRDADDR = 0x8919 + SIOCGIFCONF = 0x8912 + SIOCGIFCOUNT = 0x8938 + SIOCGIFDSTADDR = 0x8917 + SIOCGIFENCAP = 0x8925 + SIOCGIFFLAGS = 0x8913 + SIOCGIFHWADDR = 0x8927 + SIOCGIFINDEX = 0x8933 + SIOCGIFMAP = 0x8970 + SIOCGIFMEM = 0x891f + SIOCGIFMETRIC = 0x891d + SIOCGIFMTU = 0x8921 + SIOCGIFNAME = 0x8910 + SIOCGIFNETMASK = 0x891b + SIOCGIFPFLAGS = 0x8935 + SIOCGIFSLAVE = 0x8929 + SIOCGIFTXQLEN = 0x8942 + SIOCGPGRP = 0x40047309 + SIOCGRARP = 0x8961 + SIOCGSTAMP = 0x8906 + SIOCGSTAMPNS = 0x8907 + SIOCPROTOPRIVATE = 0x89e0 + SIOCRTMSG = 0x890d + SIOCSARP = 0x8955 + SIOCSIFADDR = 0x8916 + SIOCSIFBR = 0x8941 + SIOCSIFBRDADDR = 0x891a + SIOCSIFDSTADDR = 0x8918 + SIOCSIFENCAP = 0x8926 + SIOCSIFFLAGS = 0x8914 + SIOCSIFHWADDR = 0x8924 + SIOCSIFHWBROADCAST = 0x8937 + SIOCSIFLINK = 0x8911 + SIOCSIFMAP = 0x8971 + SIOCSIFMEM = 0x8920 + SIOCSIFMETRIC = 0x891e + SIOCSIFMTU = 0x8922 + SIOCSIFNAME = 0x8923 + SIOCSIFNETMASK = 0x891c + SIOCSIFPFLAGS = 0x8934 + SIOCSIFSLAVE = 0x8930 + SIOCSIFTXQLEN = 0x8943 + SIOCSPGRP = 0x80047308 + SIOCSRARP = 0x8962 + SOCK_CLOEXEC = 0x80000 + SOCK_DCCP = 0x6 + SOCK_DGRAM = 0x1 + SOCK_NONBLOCK = 0x80 + SOCK_PACKET = 0xa + SOCK_RAW = 0x3 + SOCK_RDM = 0x4 + SOCK_SEQPACKET = 0x5 + SOCK_STREAM = 0x2 + SOL_AAL = 0x109 + SOL_ALG = 0x117 + SOL_ATM = 0x108 + SOL_CAIF = 0x116 + SOL_CAN_BASE = 0x64 + SOL_DCCP = 0x10d + SOL_DECNET = 0x105 + SOL_ICMPV6 = 0x3a + SOL_IP = 0x0 + SOL_IPV6 = 0x29 + SOL_IRDA = 0x10a + SOL_IUCV = 0x115 + SOL_KCM = 0x119 + SOL_LLC = 0x10c + SOL_NETBEUI = 0x10b + SOL_NETLINK = 0x10e + SOL_NFC = 0x118 + SOL_PACKET = 0x107 + SOL_PNPIPE = 0x113 + SOL_PPPOL2TP = 0x111 + SOL_RAW = 0xff + SOL_RDS = 0x114 + SOL_RXRPC = 0x110 + SOL_SOCKET = 0xffff + SOL_TCP = 0x6 + SOL_TIPC = 0x10f + SOL_X25 = 0x106 + SOMAXCONN = 0x80 + SO_ACCEPTCONN = 0x1009 + SO_ATTACH_BPF = 0x32 + SO_ATTACH_FILTER = 0x1a + SO_ATTACH_REUSEPORT_CBPF = 0x33 + SO_ATTACH_REUSEPORT_EBPF = 0x34 + SO_BINDTODEVICE = 0x19 + SO_BPF_EXTENSIONS = 0x30 + SO_BROADCAST = 0x20 + SO_BSDCOMPAT = 0xe + SO_BUSY_POLL = 0x2e + SO_CNX_ADVICE = 0x35 + SO_DEBUG = 0x1 + SO_DETACH_BPF = 0x1b + SO_DETACH_FILTER = 0x1b + SO_DOMAIN = 0x1029 + SO_DONTROUTE = 0x10 + SO_ERROR = 0x1007 + SO_GET_FILTER = 0x1a + SO_INCOMING_CPU = 0x31 + SO_KEEPALIVE = 0x8 + SO_LINGER = 0x80 + SO_LOCK_FILTER = 0x2c + SO_MARK = 0x24 + SO_MAX_PACING_RATE = 0x2f + SO_NOFCS = 0x2b + SO_NO_CHECK = 0xb + SO_OOBINLINE = 0x100 + SO_PASSCRED = 0x11 + SO_PASSSEC = 0x22 + SO_PEEK_OFF = 0x2a + SO_PEERCRED = 0x12 + SO_PEERNAME = 0x1c + SO_PEERSEC = 0x1e + SO_PRIORITY = 0xc + SO_PROTOCOL = 0x1028 + SO_RCVBUF = 0x1002 + SO_RCVBUFFORCE = 0x21 + SO_RCVLOWAT = 0x1004 + SO_RCVTIMEO = 0x1006 + SO_REUSEADDR = 0x4 + SO_REUSEPORT = 0x200 + SO_RXQ_OVFL = 0x28 + SO_SECURITY_AUTHENTICATION = 0x16 + SO_SECURITY_ENCRYPTION_NETWORK = 0x18 + SO_SECURITY_ENCRYPTION_TRANSPORT = 0x17 + SO_SELECT_ERR_QUEUE = 0x2d + SO_SNDBUF = 0x1001 + SO_SNDBUFFORCE = 0x1f + SO_SNDLOWAT = 0x1003 + SO_SNDTIMEO = 0x1005 + SO_STYLE = 0x1008 + SO_TIMESTAMP = 0x1d + SO_TIMESTAMPING = 0x25 + SO_TIMESTAMPNS = 0x23 + SO_TYPE = 0x1008 + SO_WIFI_STATUS = 0x29 + S_BLKSIZE = 0x200 + S_IEXEC = 0x40 + S_IFBLK = 0x6000 + S_IFCHR = 0x2000 + S_IFDIR = 0x4000 + S_IFIFO = 0x1000 + S_IFLNK = 0xa000 + S_IFMT = 0xf000 + S_IFREG = 0x8000 + S_IFSOCK = 0xc000 + S_IREAD = 0x100 + S_IRGRP = 0x20 + S_IROTH = 0x4 + S_IRUSR = 0x100 + S_IRWXG = 0x38 + S_IRWXO = 0x7 + S_IRWXU = 0x1c0 + S_ISGID = 0x400 + S_ISUID = 0x800 + S_ISVTX = 0x200 + S_IWGRP = 0x10 + S_IWOTH = 0x2 + S_IWRITE = 0x80 + S_IWUSR = 0x80 + S_IXGRP = 0x8 + S_IXOTH = 0x1 + S_IXUSR = 0x40 + TAB0 = 0x0 + TAB1 = 0x800 + TAB2 = 0x1000 + TAB3 = 0x1800 + TABDLY = 0x1800 + TCFLSH = 0x5407 + TCGETA = 0x5401 + TCGETS = 0x540d + TCGETS2 = 0x4030542a + TCIFLUSH = 0x0 + TCIOFF = 0x2 + TCIOFLUSH = 0x2 + TCION = 0x3 + TCOFLUSH = 0x1 + TCOOFF = 0x0 + TCOON = 0x1 + TCP_CC_INFO = 0x1a + TCP_CONGESTION = 0xd + TCP_COOKIE_IN_ALWAYS = 0x1 + TCP_COOKIE_MAX = 0x10 + TCP_COOKIE_MIN = 0x8 + TCP_COOKIE_OUT_NEVER = 0x2 + TCP_COOKIE_PAIR_SIZE = 0x20 + TCP_COOKIE_TRANSACTIONS = 0xf + TCP_CORK = 0x3 + TCP_DEFER_ACCEPT = 0x9 + TCP_FASTOPEN = 0x17 + TCP_INFO = 0xb + TCP_KEEPCNT = 0x6 + TCP_KEEPIDLE = 0x4 + TCP_KEEPINTVL = 0x5 + TCP_LINGER2 = 0x8 + TCP_MAXSEG = 0x2 + TCP_MAXWIN = 0xffff + TCP_MAX_WINSHIFT = 0xe + TCP_MD5SIG = 0xe + TCP_MD5SIG_MAXKEYLEN = 0x50 + TCP_MSS = 0x200 + TCP_MSS_DEFAULT = 0x218 + TCP_MSS_DESIRED = 0x4c4 + TCP_NODELAY = 0x1 + TCP_NOTSENT_LOWAT = 0x19 + TCP_QUEUE_SEQ = 0x15 + TCP_QUICKACK = 0xc + TCP_REPAIR = 0x13 + TCP_REPAIR_OPTIONS = 0x16 + TCP_REPAIR_QUEUE = 0x14 + TCP_SAVED_SYN = 0x1c + TCP_SAVE_SYN = 0x1b + TCP_SYNCNT = 0x7 + TCP_S_DATA_IN = 0x4 + TCP_S_DATA_OUT = 0x8 + TCP_THIN_DUPACK = 0x11 + TCP_THIN_LINEAR_TIMEOUTS = 0x10 + TCP_TIMESTAMP = 0x18 + TCP_USER_TIMEOUT = 0x12 + TCP_WINDOW_CLAMP = 0xa + TCSAFLUSH = 0x5410 + TCSBRK = 0x5405 + TCSBRKP = 0x5486 + TCSETA = 0x5402 + TCSETAF = 0x5404 + TCSETAW = 0x5403 + TCSETS = 0x540e + TCSETS2 = 0x8030542b + TCSETSF = 0x5410 + TCSETSF2 = 0x8030542d + TCSETSW = 0x540f + TCSETSW2 = 0x8030542c + TCXONC = 0x5406 + TIOCCBRK = 0x5428 + TIOCCONS = 0x80047478 + TIOCEXCL = 0x740d + TIOCGDEV = 0x40045432 + TIOCGETD = 0x7400 + TIOCGETP = 0x7408 + TIOCGEXCL = 0x40045440 + TIOCGICOUNT = 0x5492 + TIOCGLCKTRMIOS = 0x548b + TIOCGLTC = 0x7474 + TIOCGPGRP = 0x40047477 + TIOCGPKT = 0x40045438 + TIOCGPTLCK = 0x40045439 + TIOCGPTN = 0x40045430 + TIOCGRS485 = 0x4020542e + TIOCGSERIAL = 0x5484 + TIOCGSID = 0x7416 + TIOCGSOFTCAR = 0x5481 + TIOCGWINSZ = 0x40087468 + TIOCINQ = 0x467f + TIOCLINUX = 0x5483 + TIOCMBIC = 0x741c + TIOCMBIS = 0x741b + TIOCMGET = 0x741d + TIOCMIWAIT = 0x5491 + TIOCMSET = 0x741a + TIOCM_CAR = 0x100 + TIOCM_CD = 0x100 + TIOCM_CTS = 0x40 + TIOCM_DSR = 0x400 + TIOCM_DTR = 0x2 + TIOCM_LE = 0x1 + TIOCM_RI = 0x200 + TIOCM_RNG = 0x200 + TIOCM_RTS = 0x4 + TIOCM_SR = 0x20 + TIOCM_ST = 0x10 + TIOCNOTTY = 0x5471 + TIOCNXCL = 0x740e + TIOCOUTQ = 0x7472 + TIOCPKT = 0x5470 + TIOCPKT_DATA = 0x0 + TIOCPKT_DOSTOP = 0x20 + TIOCPKT_FLUSHREAD = 0x1 + TIOCPKT_FLUSHWRITE = 0x2 + TIOCPKT_IOCTL = 0x40 + TIOCPKT_NOSTOP = 0x10 + TIOCPKT_START = 0x8 + TIOCPKT_STOP = 0x4 + TIOCSBRK = 0x5427 + TIOCSCTTY = 0x5480 + TIOCSERCONFIG = 0x5488 + TIOCSERGETLSR = 0x548e + TIOCSERGETMULTI = 0x548f + TIOCSERGSTRUCT = 0x548d + TIOCSERGWILD = 0x5489 + TIOCSERSETMULTI = 0x5490 + TIOCSERSWILD = 0x548a + TIOCSER_TEMT = 0x1 + TIOCSETD = 0x7401 + TIOCSETN = 0x740a + TIOCSETP = 0x7409 + TIOCSIG = 0x80045436 + TIOCSLCKTRMIOS = 0x548c + TIOCSLTC = 0x7475 + TIOCSPGRP = 0x80047476 + TIOCSPTLCK = 0x80045431 + TIOCSRS485 = 0xc020542f + TIOCSSERIAL = 0x5485 + TIOCSSOFTCAR = 0x5482 + TIOCSTI = 0x5472 + TIOCSWINSZ = 0x80087467 + TIOCVHANGUP = 0x5437 + TOSTOP = 0x8000 + TUNATTACHFILTER = 0x800854d5 + TUNDETACHFILTER = 0x800854d6 + TUNGETFEATURES = 0x400454cf + TUNGETFILTER = 0x400854db + TUNGETIFF = 0x400454d2 + TUNGETSNDBUF = 0x400454d3 + TUNGETVNETBE = 0x400454df + TUNGETVNETHDRSZ = 0x400454d7 + TUNGETVNETLE = 0x400454dd + TUNSETDEBUG = 0x800454c9 + TUNSETGROUP = 0x800454ce + TUNSETIFF = 0x800454ca + TUNSETIFINDEX = 0x800454da + TUNSETLINK = 0x800454cd + TUNSETNOCSUM = 0x800454c8 + TUNSETOFFLOAD = 0x800454d0 + TUNSETOWNER = 0x800454cc + TUNSETPERSIST = 0x800454cb + TUNSETQUEUE = 0x800454d9 + TUNSETSNDBUF = 0x800454d4 + TUNSETTXFILTER = 0x800454d1 + TUNSETVNETBE = 0x800454de + TUNSETVNETHDRSZ = 0x800454d8 + TUNSETVNETLE = 0x800454dc + VDISCARD = 0xd + VEOF = 0x10 + VEOL = 0x11 + VEOL2 = 0x6 + VERASE = 0x2 + VINTR = 0x0 + VKILL = 0x3 + VLNEXT = 0xf + VMIN = 0x4 + VQUIT = 0x1 + VREPRINT = 0xc + VSTART = 0x8 + VSTOP = 0x9 + VSUSP = 0xa + VSWTC = 0x7 + VSWTCH = 0x7 + VT0 = 0x0 + VT1 = 0x4000 + VTDLY = 0x4000 + VTIME = 0x5 + VWERASE = 0xe + WALL = 0x40000000 + WCLONE = 0x80000000 + WCONTINUED = 0x8 + WEXITED = 0x4 + WNOHANG = 0x1 + WNOTHREAD = 0x20000000 + WNOWAIT = 0x1000000 + WORDSIZE = 0x20 + WSTOPPED = 0x2 + WUNTRACED = 0x2 + XCASE = 0x4 + XTABS = 0x1800 +) + +// Errors +const ( + E2BIG = syscall.Errno(0x7) + EACCES = syscall.Errno(0xd) + EADDRINUSE = syscall.Errno(0x7d) + EADDRNOTAVAIL = syscall.Errno(0x7e) + EADV = syscall.Errno(0x44) + EAFNOSUPPORT = syscall.Errno(0x7c) + EAGAIN = syscall.Errno(0xb) + EALREADY = syscall.Errno(0x95) + EBADE = syscall.Errno(0x32) + EBADF = syscall.Errno(0x9) + EBADFD = syscall.Errno(0x51) + EBADMSG = syscall.Errno(0x4d) + EBADR = syscall.Errno(0x33) + EBADRQC = syscall.Errno(0x36) + EBADSLT = syscall.Errno(0x37) + EBFONT = syscall.Errno(0x3b) + EBUSY = syscall.Errno(0x10) + ECANCELED = syscall.Errno(0x9e) + ECHILD = syscall.Errno(0xa) + ECHRNG = syscall.Errno(0x25) + ECOMM = syscall.Errno(0x46) + ECONNABORTED = syscall.Errno(0x82) + ECONNREFUSED = syscall.Errno(0x92) + ECONNRESET = syscall.Errno(0x83) + EDEADLK = syscall.Errno(0x2d) + EDEADLOCK = syscall.Errno(0x38) + EDESTADDRREQ = syscall.Errno(0x60) + EDOM = syscall.Errno(0x21) + EDOTDOT = syscall.Errno(0x49) + EDQUOT = syscall.Errno(0x46d) + EEXIST = syscall.Errno(0x11) + EFAULT = syscall.Errno(0xe) + EFBIG = syscall.Errno(0x1b) + EHOSTDOWN = syscall.Errno(0x93) + EHOSTUNREACH = syscall.Errno(0x94) + EHWPOISON = syscall.Errno(0xa8) + EIDRM = syscall.Errno(0x24) + EILSEQ = syscall.Errno(0x58) + EINIT = syscall.Errno(0x8d) + EINPROGRESS = syscall.Errno(0x96) + EINTR = syscall.Errno(0x4) + EINVAL = syscall.Errno(0x16) + EIO = syscall.Errno(0x5) + EISCONN = syscall.Errno(0x85) + EISDIR = syscall.Errno(0x15) + EISNAM = syscall.Errno(0x8b) + EKEYEXPIRED = syscall.Errno(0xa2) + EKEYREJECTED = syscall.Errno(0xa4) + EKEYREVOKED = syscall.Errno(0xa3) + EL2HLT = syscall.Errno(0x2c) + EL2NSYNC = syscall.Errno(0x26) + EL3HLT = syscall.Errno(0x27) + EL3RST = syscall.Errno(0x28) + ELIBACC = syscall.Errno(0x53) + ELIBBAD = syscall.Errno(0x54) + ELIBEXEC = syscall.Errno(0x57) + ELIBMAX = syscall.Errno(0x56) + ELIBSCN = syscall.Errno(0x55) + ELNRNG = syscall.Errno(0x29) + ELOOP = syscall.Errno(0x5a) + EMEDIUMTYPE = syscall.Errno(0xa0) + EMFILE = syscall.Errno(0x18) + EMLINK = syscall.Errno(0x1f) + EMSGSIZE = syscall.Errno(0x61) + EMULTIHOP = syscall.Errno(0x4a) + ENAMETOOLONG = syscall.Errno(0x4e) + ENAVAIL = syscall.Errno(0x8a) + ENETDOWN = syscall.Errno(0x7f) + ENETRESET = syscall.Errno(0x81) + ENETUNREACH = syscall.Errno(0x80) + ENFILE = syscall.Errno(0x17) + ENOANO = syscall.Errno(0x35) + ENOBUFS = syscall.Errno(0x84) + ENOCSI = syscall.Errno(0x2b) + ENODATA = syscall.Errno(0x3d) + ENODEV = syscall.Errno(0x13) + ENOENT = syscall.Errno(0x2) + ENOEXEC = syscall.Errno(0x8) + ENOKEY = syscall.Errno(0xa1) + ENOLCK = syscall.Errno(0x2e) + ENOLINK = syscall.Errno(0x43) + ENOMEDIUM = syscall.Errno(0x9f) + ENOMEM = syscall.Errno(0xc) + ENOMSG = syscall.Errno(0x23) + ENONET = syscall.Errno(0x40) + ENOPKG = syscall.Errno(0x41) + ENOPROTOOPT = syscall.Errno(0x63) + ENOSPC = syscall.Errno(0x1c) + ENOSR = syscall.Errno(0x3f) + ENOSTR = syscall.Errno(0x3c) + ENOSYS = syscall.Errno(0x59) + ENOTBLK = syscall.Errno(0xf) + ENOTCONN = syscall.Errno(0x86) + ENOTDIR = syscall.Errno(0x14) + ENOTEMPTY = syscall.Errno(0x5d) + ENOTNAM = syscall.Errno(0x89) + ENOTRECOVERABLE = syscall.Errno(0xa6) + ENOTSOCK = syscall.Errno(0x5f) + ENOTSUP = syscall.Errno(0x7a) + ENOTTY = syscall.Errno(0x19) + ENOTUNIQ = syscall.Errno(0x50) + ENXIO = syscall.Errno(0x6) + EOPNOTSUPP = syscall.Errno(0x7a) + EOVERFLOW = syscall.Errno(0x4f) + EOWNERDEAD = syscall.Errno(0xa5) + EPERM = syscall.Errno(0x1) + EPFNOSUPPORT = syscall.Errno(0x7b) + EPIPE = syscall.Errno(0x20) + EPROTO = syscall.Errno(0x47) + EPROTONOSUPPORT = syscall.Errno(0x78) + EPROTOTYPE = syscall.Errno(0x62) + ERANGE = syscall.Errno(0x22) + EREMCHG = syscall.Errno(0x52) + EREMDEV = syscall.Errno(0x8e) + EREMOTE = syscall.Errno(0x42) + EREMOTEIO = syscall.Errno(0x8c) + ERESTART = syscall.Errno(0x5b) + ERFKILL = syscall.Errno(0xa7) + EROFS = syscall.Errno(0x1e) + ESHUTDOWN = syscall.Errno(0x8f) + ESOCKTNOSUPPORT = syscall.Errno(0x79) + ESPIPE = syscall.Errno(0x1d) + ESRCH = syscall.Errno(0x3) + ESRMNT = syscall.Errno(0x45) + ESTALE = syscall.Errno(0x97) + ESTRPIPE = syscall.Errno(0x5c) + ETIME = syscall.Errno(0x3e) + ETIMEDOUT = syscall.Errno(0x91) + ETOOMANYREFS = syscall.Errno(0x90) + ETXTBSY = syscall.Errno(0x1a) + EUCLEAN = syscall.Errno(0x87) + EUNATCH = syscall.Errno(0x2a) + EUSERS = syscall.Errno(0x5e) + EWOULDBLOCK = syscall.Errno(0xb) + EXDEV = syscall.Errno(0x12) + EXFULL = syscall.Errno(0x34) +) + +// Signals +const ( + SIGABRT = syscall.Signal(0x6) + SIGALRM = syscall.Signal(0xe) + SIGBUS = syscall.Signal(0xa) + SIGCHLD = syscall.Signal(0x12) + SIGCLD = syscall.Signal(0x12) + SIGCONT = syscall.Signal(0x19) + SIGEMT = syscall.Signal(0x7) + SIGFPE = syscall.Signal(0x8) + SIGHUP = syscall.Signal(0x1) + SIGILL = syscall.Signal(0x4) + SIGINT = syscall.Signal(0x2) + SIGIO = syscall.Signal(0x16) + SIGIOT = syscall.Signal(0x6) + SIGKILL = syscall.Signal(0x9) + SIGPIPE = syscall.Signal(0xd) + SIGPOLL = syscall.Signal(0x16) + SIGPROF = syscall.Signal(0x1d) + SIGPWR = syscall.Signal(0x13) + SIGQUIT = syscall.Signal(0x3) + SIGSEGV = syscall.Signal(0xb) + SIGSTOP = syscall.Signal(0x17) + SIGSYS = syscall.Signal(0xc) + SIGTERM = syscall.Signal(0xf) + SIGTRAP = syscall.Signal(0x5) + SIGTSTP = syscall.Signal(0x18) + SIGTTIN = syscall.Signal(0x1a) + SIGTTOU = syscall.Signal(0x1b) + SIGURG = syscall.Signal(0x15) + SIGUSR1 = syscall.Signal(0x10) + SIGUSR2 = syscall.Signal(0x11) + SIGVTALRM = syscall.Signal(0x1c) + SIGWINCH = syscall.Signal(0x14) + SIGXCPU = syscall.Signal(0x1e) + SIGXFSZ = syscall.Signal(0x1f) +) + +// Error table +var errors = [...]string{ + 1: "operation not permitted", + 2: "no such file or directory", + 3: "no such process", + 4: "interrupted system call", + 5: "input/output error", + 6: "no such device or address", + 7: "argument list too long", + 8: "exec format error", + 9: "bad file descriptor", + 10: "no child processes", + 11: "resource temporarily unavailable", + 12: "cannot allocate memory", + 13: "permission denied", + 14: "bad address", + 15: "block device required", + 16: "device or resource busy", + 17: "file exists", + 18: "invalid cross-device link", + 19: "no such device", + 20: "not a directory", + 21: "is a directory", + 22: "invalid argument", + 23: "too many open files in system", + 24: "too many open files", + 25: "inappropriate ioctl for device", + 26: "text file busy", + 27: "file too large", + 28: "no space left on device", + 29: "illegal seek", + 30: "read-only file system", + 31: "too many links", + 32: "broken pipe", + 33: "numerical argument out of domain", + 34: "numerical result out of range", + 35: "no message of desired type", + 36: "identifier removed", + 37: "channel number out of range", + 38: "level 2 not synchronized", + 39: "level 3 halted", + 40: "level 3 reset", + 41: "link number out of range", + 42: "protocol driver not attached", + 43: "no CSI structure available", + 44: "level 2 halted", + 45: "resource deadlock avoided", + 46: "no locks available", + 50: "invalid exchange", + 51: "invalid request descriptor", + 52: "exchange full", + 53: "no anode", + 54: "invalid request code", + 55: "invalid slot", + 56: "file locking deadlock error", + 59: "bad font file format", + 60: "device not a stream", + 61: "no data available", + 62: "timer expired", + 63: "out of streams resources", + 64: "machine is not on the network", + 65: "package not installed", + 66: "object is remote", + 67: "link has been severed", + 68: "advertise error", + 69: "srmount error", + 70: "communication error on send", + 71: "protocol error", + 73: "RFS specific error", + 74: "multihop attempted", + 77: "bad message", + 78: "file name too long", + 79: "value too large for defined data type", + 80: "name not unique on network", + 81: "file descriptor in bad state", + 82: "remote address changed", + 83: "can not access a needed shared library", + 84: "accessing a corrupted shared library", + 85: ".lib section in a.out corrupted", + 86: "attempting to link in too many shared libraries", + 87: "cannot exec a shared library directly", + 88: "invalid or incomplete multibyte or wide character", + 89: "function not implemented", + 90: "too many levels of symbolic links", + 91: "interrupted system call should be restarted", + 92: "streams pipe error", + 93: "directory not empty", + 94: "too many users", + 95: "socket operation on non-socket", + 96: "destination address required", + 97: "message too long", + 98: "protocol wrong type for socket", + 99: "protocol not available", + 120: "protocol not supported", + 121: "socket type not supported", + 122: "operation not supported", + 123: "protocol family not supported", + 124: "address family not supported by protocol", + 125: "address already in use", + 126: "cannot assign requested address", + 127: "network is down", + 128: "network is unreachable", + 129: "network dropped connection on reset", + 130: "software caused connection abort", + 131: "connection reset by peer", + 132: "no buffer space available", + 133: "transport endpoint is already connected", + 134: "transport endpoint is not connected", + 135: "structure needs cleaning", + 137: "not a XENIX named type file", + 138: "no XENIX semaphores available", + 139: "is a named type file", + 140: "remote I/O error", + 141: "unknown error 141", + 142: "unknown error 142", + 143: "cannot send after transport endpoint shutdown", + 144: "too many references: cannot splice", + 145: "connection timed out", + 146: "connection refused", + 147: "host is down", + 148: "no route to host", + 149: "operation already in progress", + 150: "operation now in progress", + 151: "stale file handle", + 158: "operation canceled", + 159: "no medium found", + 160: "wrong medium type", + 161: "required key not available", + 162: "key has expired", + 163: "key has been revoked", + 164: "key was rejected by service", + 165: "owner died", + 166: "state not recoverable", + 167: "operation not possible due to RF-kill", + 168: "memory page has hardware error", + 1133: "disk quota exceeded", +} + +// Signal table +var signals = [...]string{ + 1: "hangup", + 2: "interrupt", + 3: "quit", + 4: "illegal instruction", + 5: "trace/breakpoint trap", + 6: "aborted", + 7: "EMT trap", + 8: "floating point exception", + 9: "killed", + 10: "bus error", + 11: "segmentation fault", + 12: "bad system call", + 13: "broken pipe", + 14: "alarm clock", + 15: "terminated", + 16: "user defined signal 1", + 17: "user defined signal 2", + 18: "child exited", + 19: "power failure", + 20: "window changed", + 21: "urgent I/O condition", + 22: "I/O possible", + 23: "stopped (signal)", + 24: "stopped", + 25: "continued", + 26: "stopped (tty input)", + 27: "stopped (tty output)", + 28: "virtual timer expired", + 29: "profiling timer expired", + 30: "CPU time limit exceeded", + 31: "file size limit exceeded", +} diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64.go b/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64.go index 8b42ca2..4e41939 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64.go @@ -197,6 +197,25 @@ const ( BS0 = 0x0 BS1 = 0x8000 BSDLY = 0x8000 + CAN_BCM = 0x2 + CAN_EFF_FLAG = 0x80000000 + CAN_EFF_ID_BITS = 0x1d + CAN_EFF_MASK = 0x1fffffff + CAN_ERR_FLAG = 0x20000000 + CAN_ERR_MASK = 0x1fffffff + CAN_INV_FILTER = 0x20000000 + CAN_ISOTP = 0x6 + CAN_MAX_DLC = 0x8 + CAN_MAX_DLEN = 0x8 + CAN_MCNET = 0x5 + CAN_MTU = 0x10 + CAN_NPROTO = 0x7 + CAN_RAW = 0x1 + CAN_RTR_FLAG = 0x40000000 + CAN_SFF_ID_BITS = 0xb + CAN_SFF_MASK = 0x7ff + CAN_TP16 = 0x3 + CAN_TP20 = 0x4 CBAUD = 0xff CBAUDEX = 0x0 CFLUSH = 0xf diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64le.go b/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64le.go index e8d12b5..407e6b5 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64le.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64le.go @@ -196,6 +196,25 @@ const ( BS0 = 0x0 BS1 = 0x8000 BSDLY = 0x8000 + CAN_BCM = 0x2 + CAN_EFF_FLAG = 0x80000000 + CAN_EFF_ID_BITS = 0x1d + CAN_EFF_MASK = 0x1fffffff + CAN_ERR_FLAG = 0x20000000 + CAN_ERR_MASK = 0x1fffffff + CAN_INV_FILTER = 0x20000000 + CAN_ISOTP = 0x6 + CAN_MAX_DLC = 0x8 + CAN_MAX_DLEN = 0x8 + CAN_MCNET = 0x5 + CAN_MTU = 0x10 + CAN_NPROTO = 0x7 + CAN_RAW = 0x1 + CAN_RTR_FLAG = 0x40000000 + CAN_SFF_ID_BITS = 0xb + CAN_SFF_MASK = 0x7ff + CAN_TP16 = 0x3 + CAN_TP20 = 0x4 CBAUD = 0xff CBAUDEX = 0x0 CFLUSH = 0xf diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_s390x.go b/vendor/golang.org/x/sys/unix/zerrors_linux_s390x.go index 329f25e..40c9b87 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_s390x.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_s390x.go @@ -201,6 +201,25 @@ const ( BS0 = 0x0 BS1 = 0x2000 BSDLY = 0x2000 + CAN_BCM = 0x2 + CAN_EFF_FLAG = 0x80000000 + CAN_EFF_ID_BITS = 0x1d + CAN_EFF_MASK = 0x1fffffff + CAN_ERR_FLAG = 0x20000000 + CAN_ERR_MASK = 0x1fffffff + CAN_INV_FILTER = 0x20000000 + CAN_ISOTP = 0x6 + CAN_MAX_DLC = 0x8 + CAN_MAX_DLEN = 0x8 + CAN_MCNET = 0x5 + CAN_MTU = 0x10 + CAN_NPROTO = 0x7 + CAN_RAW = 0x1 + CAN_RTR_FLAG = 0x40000000 + CAN_SFF_ID_BITS = 0xb + CAN_SFF_MASK = 0x7ff + CAN_TP16 = 0x3 + CAN_TP20 = 0x4 CBAUD = 0x100f CBAUDEX = 0x1000 CFLUSH = 0xf diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_sparc64.go b/vendor/golang.org/x/sys/unix/zerrors_linux_sparc64.go index 766d1e6..62680ed 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_sparc64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_sparc64.go @@ -205,6 +205,25 @@ const ( BS0 = 0x0 BS1 = 0x2000 BSDLY = 0x2000 + CAN_BCM = 0x2 + CAN_EFF_FLAG = 0x80000000 + CAN_EFF_ID_BITS = 0x1d + CAN_EFF_MASK = 0x1fffffff + CAN_ERR_FLAG = 0x20000000 + CAN_ERR_MASK = 0x1fffffff + CAN_INV_FILTER = 0x20000000 + CAN_ISOTP = 0x6 + CAN_MAX_DLC = 0x8 + CAN_MAX_DLEN = 0x8 + CAN_MCNET = 0x5 + CAN_MTU = 0x10 + CAN_NPROTO = 0x7 + CAN_RAW = 0x1 + CAN_RTR_FLAG = 0x40000000 + CAN_SFF_ID_BITS = 0xb + CAN_SFF_MASK = 0x7ff + CAN_TP16 = 0x3 + CAN_TP20 = 0x4 CBAUD = 0x100f CBAUDEX = 0x1000 CFLUSH = 0xf diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux_386.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_386.go index 80f6a1b..fa92387 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux_386.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_386.go @@ -572,6 +572,17 @@ func Getrusage(who int, rusage *Rusage) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Getsid(pid int) (sid int, err error) { + r0, _, e1 := RawSyscall(SYS_GETSID, uintptr(pid), 0, 0) + sid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Gettid() (tid int) { r0, _, _ := RawSyscall(SYS_GETTID, 0, 0, 0) tid = int(r0) @@ -762,8 +773,8 @@ func PivotRoot(newroot string, putold string) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func prlimit(pid int, resource int, old *Rlimit, newlimit *Rlimit) (err error) { - _, _, e1 := RawSyscall6(SYS_PRLIMIT64, uintptr(pid), uintptr(resource), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(newlimit)), 0, 0) +func prlimit(pid int, resource int, newlimit *Rlimit, old *Rlimit) (err error) { + _, _, e1 := RawSyscall6(SYS_PRLIMIT64, uintptr(pid), uintptr(resource), uintptr(unsafe.Pointer(newlimit)), uintptr(unsafe.Pointer(old)), 0, 0) if e1 != 0 { err = errnoErr(e1) } diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux_amd64.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_amd64.go index 078c8f0..b34d5c2 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux_amd64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_amd64.go @@ -572,6 +572,17 @@ func Getrusage(who int, rusage *Rusage) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Getsid(pid int) (sid int, err error) { + r0, _, e1 := RawSyscall(SYS_GETSID, uintptr(pid), 0, 0) + sid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Gettid() (tid int) { r0, _, _ := RawSyscall(SYS_GETTID, 0, 0, 0) tid = int(r0) @@ -762,8 +773,8 @@ func PivotRoot(newroot string, putold string) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func prlimit(pid int, resource int, old *Rlimit, newlimit *Rlimit) (err error) { - _, _, e1 := RawSyscall6(SYS_PRLIMIT64, uintptr(pid), uintptr(resource), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(newlimit)), 0, 0) +func prlimit(pid int, resource int, newlimit *Rlimit, old *Rlimit) (err error) { + _, _, e1 := RawSyscall6(SYS_PRLIMIT64, uintptr(pid), uintptr(resource), uintptr(unsafe.Pointer(newlimit)), uintptr(unsafe.Pointer(old)), 0, 0) if e1 != 0 { err = errnoErr(e1) } diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux_arm.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_arm.go index 76e5f7c..2e5cb39 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux_arm.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_arm.go @@ -572,6 +572,17 @@ func Getrusage(who int, rusage *Rusage) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Getsid(pid int) (sid int, err error) { + r0, _, e1 := RawSyscall(SYS_GETSID, uintptr(pid), 0, 0) + sid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Gettid() (tid int) { r0, _, _ := RawSyscall(SYS_GETTID, 0, 0, 0) tid = int(r0) @@ -762,8 +773,8 @@ func PivotRoot(newroot string, putold string) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func prlimit(pid int, resource int, old *Rlimit, newlimit *Rlimit) (err error) { - _, _, e1 := RawSyscall6(SYS_PRLIMIT64, uintptr(pid), uintptr(resource), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(newlimit)), 0, 0) +func prlimit(pid int, resource int, newlimit *Rlimit, old *Rlimit) (err error) { + _, _, e1 := RawSyscall6(SYS_PRLIMIT64, uintptr(pid), uintptr(resource), uintptr(unsafe.Pointer(newlimit)), uintptr(unsafe.Pointer(old)), 0, 0) if e1 != 0 { err = errnoErr(e1) } diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux_arm64.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_arm64.go index 72b7947..0d584cc 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux_arm64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_arm64.go @@ -572,6 +572,17 @@ func Getrusage(who int, rusage *Rusage) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Getsid(pid int) (sid int, err error) { + r0, _, e1 := RawSyscall(SYS_GETSID, uintptr(pid), 0, 0) + sid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Gettid() (tid int) { r0, _, _ := RawSyscall(SYS_GETTID, 0, 0, 0) tid = int(r0) @@ -762,8 +773,8 @@ func PivotRoot(newroot string, putold string) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func prlimit(pid int, resource int, old *Rlimit, newlimit *Rlimit) (err error) { - _, _, e1 := RawSyscall6(SYS_PRLIMIT64, uintptr(pid), uintptr(resource), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(newlimit)), 0, 0) +func prlimit(pid int, resource int, newlimit *Rlimit, old *Rlimit) (err error) { + _, _, e1 := RawSyscall6(SYS_PRLIMIT64, uintptr(pid), uintptr(resource), uintptr(unsafe.Pointer(newlimit)), uintptr(unsafe.Pointer(old)), 0, 0) if e1 != 0 { err = errnoErr(e1) } diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux_mips.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_mips.go new file mode 100644 index 0000000..a18e0b1 --- /dev/null +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_mips.go @@ -0,0 +1,1829 @@ +// mksyscall.pl -b32 -arm syscall_linux.go syscall_linux_mipsx.go +// MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT + +// +build mips,linux + +package unix + +import ( + "syscall" + "unsafe" +) + +var _ syscall.Errno + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Linkat(olddirfd int, oldpath string, newdirfd int, newpath string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(oldpath) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(newpath) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_LINKAT, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), uintptr(flags), 0) + use(unsafe.Pointer(_p0)) + use(unsafe.Pointer(_p1)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func openat(dirfd int, path string, flags int, mode uint32) (fd int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_OPENAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags), uintptr(mode), 0, 0) + use(unsafe.Pointer(_p0)) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func ppoll(fds *PollFd, nfds int, timeout *Timespec, sigmask *Sigset_t) (n int, err error) { + r0, _, e1 := Syscall6(SYS_PPOLL, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(unsafe.Pointer(timeout)), uintptr(unsafe.Pointer(sigmask)), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Readlinkat(dirfd int, path string, buf []byte) (n int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 unsafe.Pointer + if len(buf) > 0 { + _p1 = unsafe.Pointer(&buf[0]) + } else { + _p1 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_READLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf)), 0, 0) + use(unsafe.Pointer(_p0)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Symlinkat(oldpath string, newdirfd int, newpath string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(oldpath) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(newpath) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_SYMLINKAT, uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1))) + use(unsafe.Pointer(_p0)) + use(unsafe.Pointer(_p1)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Unlinkat(dirfd int, path string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_UNLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags)) + use(unsafe.Pointer(_p0)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func utimes(path string, times *[2]Timeval) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), 0) + use(unsafe.Pointer(_p0)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_UTIMENSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), uintptr(flags), 0, 0) + use(unsafe.Pointer(_p0)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func futimesat(dirfd int, path *byte, times *[2]Timeval) (err error) { + _, _, e1 := Syscall(SYS_FUTIMESAT, uintptr(dirfd), uintptr(unsafe.Pointer(path)), uintptr(unsafe.Pointer(times))) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Getcwd(buf []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall(SYS_GETCWD, uintptr(_p0), uintptr(len(buf)), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) { + r0, _, e1 := Syscall6(SYS_WAIT4, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0) + wpid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func ptrace(request int, pid int, addr uintptr, data uintptr) (err error) { + _, _, e1 := Syscall6(SYS_PTRACE, uintptr(request), uintptr(pid), uintptr(addr), uintptr(data), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func reboot(magic1 uint, magic2 uint, cmd int, arg string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(arg) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_REBOOT, uintptr(magic1), uintptr(magic2), uintptr(cmd), uintptr(unsafe.Pointer(_p0)), 0, 0) + use(unsafe.Pointer(_p0)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func mount(source string, target string, fstype string, flags uintptr, data *byte) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(source) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(target) + if err != nil { + return + } + var _p2 *byte + _p2, err = BytePtrFromString(fstype) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_MOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(unsafe.Pointer(_p2)), uintptr(flags), uintptr(unsafe.Pointer(data)), 0) + use(unsafe.Pointer(_p0)) + use(unsafe.Pointer(_p1)) + use(unsafe.Pointer(_p2)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Acct(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_ACCT, uintptr(unsafe.Pointer(_p0)), 0, 0) + use(unsafe.Pointer(_p0)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Adjtimex(buf *Timex) (state int, err error) { + r0, _, e1 := Syscall(SYS_ADJTIMEX, uintptr(unsafe.Pointer(buf)), 0, 0) + state = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Chdir(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_CHDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) + use(unsafe.Pointer(_p0)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Chroot(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) + use(unsafe.Pointer(_p0)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func ClockGettime(clockid int32, time *Timespec) (err error) { + _, _, e1 := Syscall(SYS_CLOCK_GETTIME, uintptr(clockid), uintptr(unsafe.Pointer(time)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Close(fd int) (err error) { + _, _, e1 := Syscall(SYS_CLOSE, uintptr(fd), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Dup(oldfd int) (fd int, err error) { + r0, _, e1 := Syscall(SYS_DUP, uintptr(oldfd), 0, 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Dup3(oldfd int, newfd int, flags int) (err error) { + _, _, e1 := Syscall(SYS_DUP3, uintptr(oldfd), uintptr(newfd), uintptr(flags)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func EpollCreate(size int) (fd int, err error) { + r0, _, e1 := RawSyscall(SYS_EPOLL_CREATE, uintptr(size), 0, 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func EpollCreate1(flag int) (fd int, err error) { + r0, _, e1 := RawSyscall(SYS_EPOLL_CREATE1, uintptr(flag), 0, 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func EpollCtl(epfd int, op int, fd int, event *EpollEvent) (err error) { + _, _, e1 := RawSyscall6(SYS_EPOLL_CTL, uintptr(epfd), uintptr(op), uintptr(fd), uintptr(unsafe.Pointer(event)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Exit(code int) { + Syscall(SYS_EXIT_GROUP, uintptr(code), 0, 0) + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_FACCESSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) + use(unsafe.Pointer(_p0)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Fallocate(fd int, mode uint32, off int64, len int64) (err error) { + _, _, e1 := Syscall6(SYS_FALLOCATE, uintptr(fd), uintptr(mode), uintptr(off>>32), uintptr(off), uintptr(len>>32), uintptr(len)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Fchdir(fd int) (err error) { + _, _, e1 := Syscall(SYS_FCHDIR, uintptr(fd), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Fchmod(fd int, mode uint32) (err error) { + _, _, e1 := Syscall(SYS_FCHMOD, uintptr(fd), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_FCHMODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) + use(unsafe.Pointer(_p0)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_FCHOWNAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid), uintptr(flags), 0) + use(unsafe.Pointer(_p0)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func fcntl(fd int, cmd int, arg int) (val int, err error) { + r0, _, e1 := Syscall(SYS_FCNTL, uintptr(fd), uintptr(cmd), uintptr(arg)) + val = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Fdatasync(fd int) (err error) { + _, _, e1 := Syscall(SYS_FDATASYNC, uintptr(fd), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Flock(fd int, how int) (err error) { + _, _, e1 := Syscall(SYS_FLOCK, uintptr(fd), uintptr(how), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Fsync(fd int) (err error) { + _, _, e1 := Syscall(SYS_FSYNC, uintptr(fd), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Getdents(fd int, buf []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall(SYS_GETDENTS64, uintptr(fd), uintptr(_p0), uintptr(len(buf))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Getpgid(pid int) (pgid int, err error) { + r0, _, e1 := RawSyscall(SYS_GETPGID, uintptr(pid), 0, 0) + pgid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Getpid() (pid int) { + r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0) + pid = int(r0) + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Getppid() (ppid int) { + r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0) + ppid = int(r0) + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Getpriority(which int, who int) (prio int, err error) { + r0, _, e1 := Syscall(SYS_GETPRIORITY, uintptr(which), uintptr(who), 0) + prio = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Getrusage(who int, rusage *Rusage) (err error) { + _, _, e1 := RawSyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Getsid(pid int) (sid int, err error) { + r0, _, e1 := RawSyscall(SYS_GETSID, uintptr(pid), 0, 0) + sid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Gettid() (tid int) { + r0, _, _ := RawSyscall(SYS_GETTID, 0, 0, 0) + tid = int(r0) + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Getxattr(path string, attr string, dest []byte) (sz int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attr) + if err != nil { + return + } + var _p2 unsafe.Pointer + if len(dest) > 0 { + _p2 = unsafe.Pointer(&dest[0]) + } else { + _p2 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_GETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(dest)), 0, 0) + use(unsafe.Pointer(_p0)) + use(unsafe.Pointer(_p1)) + sz = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func InotifyAddWatch(fd int, pathname string, mask uint32) (watchdesc int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(pathname) + if err != nil { + return + } + r0, _, e1 := Syscall(SYS_INOTIFY_ADD_WATCH, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(mask)) + use(unsafe.Pointer(_p0)) + watchdesc = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func InotifyInit1(flags int) (fd int, err error) { + r0, _, e1 := RawSyscall(SYS_INOTIFY_INIT1, uintptr(flags), 0, 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func InotifyRmWatch(fd int, watchdesc uint32) (success int, err error) { + r0, _, e1 := RawSyscall(SYS_INOTIFY_RM_WATCH, uintptr(fd), uintptr(watchdesc), 0) + success = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Kill(pid int, sig syscall.Signal) (err error) { + _, _, e1 := RawSyscall(SYS_KILL, uintptr(pid), uintptr(sig), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Klogctl(typ int, buf []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall(SYS_SYSLOG, uintptr(typ), uintptr(_p0), uintptr(len(buf))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Listxattr(path string, dest []byte) (sz int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 unsafe.Pointer + if len(dest) > 0 { + _p1 = unsafe.Pointer(&dest[0]) + } else { + _p1 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall(SYS_LISTXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(dest))) + use(unsafe.Pointer(_p0)) + sz = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Mkdirat(dirfd int, path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_MKDIRAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) + use(unsafe.Pointer(_p0)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Mknodat(dirfd int, path string, mode uint32, dev int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_MKNODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev), 0, 0) + use(unsafe.Pointer(_p0)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Nanosleep(time *Timespec, leftover *Timespec) (err error) { + _, _, e1 := Syscall(SYS_NANOSLEEP, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func PivotRoot(newroot string, putold string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(newroot) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(putold) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_PIVOT_ROOT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) + use(unsafe.Pointer(_p0)) + use(unsafe.Pointer(_p1)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func prlimit(pid int, resource int, newlimit *Rlimit, old *Rlimit) (err error) { + _, _, e1 := RawSyscall6(SYS_PRLIMIT64, uintptr(pid), uintptr(resource), uintptr(unsafe.Pointer(newlimit)), uintptr(unsafe.Pointer(old)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Prctl(option int, arg2 uintptr, arg3 uintptr, arg4 uintptr, arg5 uintptr) (err error) { + _, _, e1 := Syscall6(SYS_PRCTL, uintptr(option), uintptr(arg2), uintptr(arg3), uintptr(arg4), uintptr(arg5), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func read(fd int, p []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(_p0), uintptr(len(p))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Removexattr(path string, attr string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attr) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_REMOVEXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) + use(unsafe.Pointer(_p0)) + use(unsafe.Pointer(_p1)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(oldpath) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(newpath) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_RENAMEAT, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), 0, 0) + use(unsafe.Pointer(_p0)) + use(unsafe.Pointer(_p1)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Setdomainname(p []byte) (err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_SETDOMAINNAME, uintptr(_p0), uintptr(len(p)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Sethostname(p []byte) (err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_SETHOSTNAME, uintptr(_p0), uintptr(len(p)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Setpgid(pid int, pgid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETPGID, uintptr(pid), uintptr(pgid), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Setsid() (pid int, err error) { + r0, _, e1 := RawSyscall(SYS_SETSID, 0, 0, 0) + pid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Settimeofday(tv *Timeval) (err error) { + _, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Setns(fd int, nstype int) (err error) { + _, _, e1 := Syscall(SYS_SETNS, uintptr(fd), uintptr(nstype), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Setpriority(which int, who int, prio int) (err error) { + _, _, e1 := Syscall(SYS_SETPRIORITY, uintptr(which), uintptr(who), uintptr(prio)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Setxattr(path string, attr string, data []byte, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attr) + if err != nil { + return + } + var _p2 unsafe.Pointer + if len(data) > 0 { + _p2 = unsafe.Pointer(&data[0]) + } else { + _p2 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall6(SYS_SETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(data)), uintptr(flags), 0) + use(unsafe.Pointer(_p0)) + use(unsafe.Pointer(_p1)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Sync() { + Syscall(SYS_SYNC, 0, 0, 0) + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Sysinfo(info *Sysinfo_t) (err error) { + _, _, e1 := RawSyscall(SYS_SYSINFO, uintptr(unsafe.Pointer(info)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Tee(rfd int, wfd int, len int, flags int) (n int64, err error) { + r0, r1, e1 := Syscall6(SYS_TEE, uintptr(rfd), uintptr(wfd), uintptr(len), uintptr(flags), 0, 0) + n = int64(int64(r0)<<32 | int64(r1)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Tgkill(tgid int, tid int, sig syscall.Signal) (err error) { + _, _, e1 := RawSyscall(SYS_TGKILL, uintptr(tgid), uintptr(tid), uintptr(sig)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Times(tms *Tms) (ticks uintptr, err error) { + r0, _, e1 := RawSyscall(SYS_TIMES, uintptr(unsafe.Pointer(tms)), 0, 0) + ticks = uintptr(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Umask(mask int) (oldmask int) { + r0, _, _ := RawSyscall(SYS_UMASK, uintptr(mask), 0, 0) + oldmask = int(r0) + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Uname(buf *Utsname) (err error) { + _, _, e1 := RawSyscall(SYS_UNAME, uintptr(unsafe.Pointer(buf)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Unmount(target string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(target) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_UMOUNT2, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) + use(unsafe.Pointer(_p0)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Unshare(flags int) (err error) { + _, _, e1 := Syscall(SYS_UNSHARE, uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Ustat(dev int, ubuf *Ustat_t) (err error) { + _, _, e1 := Syscall(SYS_USTAT, uintptr(dev), uintptr(unsafe.Pointer(ubuf)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func write(fd int, p []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(_p0), uintptr(len(p))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func exitThread(code int) (err error) { + _, _, e1 := Syscall(SYS_EXIT, uintptr(code), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func readlen(fd int, p *byte, np int) (n int, err error) { + r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(p)), uintptr(np)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func writelen(fd int, p *byte, np int) (n int, err error) { + r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(unsafe.Pointer(p)), uintptr(np)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func munmap(addr uintptr, length uintptr) (err error) { + _, _, e1 := Syscall(SYS_MUNMAP, uintptr(addr), uintptr(length), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Madvise(b []byte, advice int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MADVISE, uintptr(_p0), uintptr(len(b)), uintptr(advice)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Mprotect(b []byte, prot int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Mlock(b []byte) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Munlock(b []byte) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Mlockall(flags int) (err error) { + _, _, e1 := Syscall(SYS_MLOCKALL, uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Munlockall() (err error) { + _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Dup2(oldfd int, newfd int) (err error) { + _, _, e1 := Syscall(SYS_DUP2, uintptr(oldfd), uintptr(newfd), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Fchown(fd int, uid int, gid int) (err error) { + _, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Ftruncate(fd int, length int64) (err error) { + _, _, e1 := Syscall6(SYS_FTRUNCATE64, uintptr(fd), 0, uintptr(length>>32), uintptr(length), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Getegid() (egid int) { + r0, _, _ := RawSyscall(SYS_GETEGID, 0, 0, 0) + egid = int(r0) + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Geteuid() (euid int) { + r0, _, _ := RawSyscall(SYS_GETEUID, 0, 0, 0) + euid = int(r0) + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Getgid() (gid int) { + r0, _, _ := RawSyscall(SYS_GETGID, 0, 0, 0) + gid = int(r0) + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Getuid() (uid int) { + r0, _, _ := RawSyscall(SYS_GETUID, 0, 0, 0) + uid = int(r0) + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Lchown(path string, uid int, gid int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_LCHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) + use(unsafe.Pointer(_p0)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Listen(s int, n int) (err error) { + _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(n), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Pread(fd int, p []byte, offset int64) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_PREAD64, uintptr(fd), uintptr(_p0), uintptr(len(p)), 0, uintptr(offset>>32), uintptr(offset)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Pwrite(fd int, p []byte, offset int64) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_PWRITE64, uintptr(fd), uintptr(_p0), uintptr(len(p)), 0, uintptr(offset>>32), uintptr(offset)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) { + r0, _, e1 := Syscall6(SYS__NEWSELECT, uintptr(nfd), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) { + r0, _, e1 := Syscall6(SYS_SENDFILE64, uintptr(outfd), uintptr(infd), uintptr(unsafe.Pointer(offset)), uintptr(count), 0, 0) + written = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Setfsgid(gid int) (err error) { + _, _, e1 := Syscall(SYS_SETFSGID, uintptr(gid), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Setfsuid(uid int) (err error) { + _, _, e1 := Syscall(SYS_SETFSUID, uintptr(uid), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Setregid(rgid int, egid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETREGID, uintptr(rgid), uintptr(egid), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Setresgid(rgid int, egid int, sgid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETRESGID, uintptr(rgid), uintptr(egid), uintptr(sgid)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Setresuid(ruid int, euid int, suid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETRESUID, uintptr(ruid), uintptr(euid), uintptr(suid)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Setreuid(ruid int, euid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETREUID, uintptr(ruid), uintptr(euid), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Shutdown(fd int, how int) (err error) { + _, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(fd), uintptr(how), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int64, err error) { + r0, r1, e1 := Syscall6(SYS_SPLICE, uintptr(rfd), uintptr(unsafe.Pointer(roff)), uintptr(wfd), uintptr(unsafe.Pointer(woff)), uintptr(len), uintptr(flags)) + n = int64(int64(r0)<<32 | int64(r1)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func SyncFileRange(fd int, off int64, n int64, flags int) (err error) { + _, _, e1 := Syscall9(SYS_SYNC_FILE_RANGE, uintptr(fd), 0, uintptr(off>>32), uintptr(off), uintptr(n>>32), uintptr(n), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Truncate(path string, length int64) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_TRUNCATE64, uintptr(unsafe.Pointer(_p0)), 0, uintptr(length>>32), uintptr(length), 0, 0) + use(unsafe.Pointer(_p0)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) { + r0, _, e1 := Syscall(SYS_ACCEPT, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func accept4(s int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (fd int, err error) { + r0, _, e1 := Syscall6(SYS_ACCEPT4, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), uintptr(flags), 0, 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { + _, _, e1 := Syscall(SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { + _, _, e1 := Syscall(SYS_CONNECT, uintptr(s), uintptr(addr), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func getgroups(n int, list *_Gid_t) (nn int, err error) { + r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(n), uintptr(unsafe.Pointer(list)), 0) + nn = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func setgroups(n int, list *_Gid_t) (err error) { + _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(n), uintptr(unsafe.Pointer(list)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { + _, _, e1 := Syscall6(SYS_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { + _, _, e1 := Syscall6(SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func socket(domain int, typ int, proto int) (fd int, err error) { + r0, _, e1 := RawSyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto)) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { + _, _, e1 := RawSyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { + _, _, e1 := RawSyscall(SYS_GETPEERNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { + _, _, e1 := RawSyscall(SYS_GETSOCKNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_RECVFROM, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall6(SYS_SENDTO, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { + r0, _, e1 := Syscall(SYS_RECVMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { + r0, _, e1 := Syscall(SYS_SENDMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func InotifyInit() (fd int, err error) { + r0, _, e1 := RawSyscall(SYS_INOTIFY_INIT, 0, 0, 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Ioperm(from int, num int, on int) (err error) { + _, _, e1 := Syscall(SYS_IOPERM, uintptr(from), uintptr(num), uintptr(on)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Iopl(level int) (err error) { + _, _, e1 := Syscall(SYS_IOPL, uintptr(level), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Gettimeofday(tv *Timeval) (err error) { + _, _, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Time(t *Time_t) (tt Time_t, err error) { + r0, _, e1 := RawSyscall(SYS_TIME, uintptr(unsafe.Pointer(t)), 0, 0) + tt = Time_t(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Lstat(path string, stat *Stat_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_LSTAT64, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) + use(unsafe.Pointer(_p0)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Fstat(fd int, stat *Stat_t) (err error) { + _, _, e1 := Syscall(SYS_FSTAT64, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Stat(path string, stat *Stat_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_STAT64, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) + use(unsafe.Pointer(_p0)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Utime(path string, buf *Utimbuf) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_UTIME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(buf)), 0) + use(unsafe.Pointer(_p0)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) { + var _p0 unsafe.Pointer + if len(events) > 0 { + _p0 = unsafe.Pointer(&events[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_EPOLL_WAIT, uintptr(epfd), uintptr(_p0), uintptr(len(events)), uintptr(msec), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Pause() (err error) { + _, _, e1 := Syscall(SYS_PAUSE, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func pipe2(p *[2]_C_int, flags int) (err error) { + _, _, e1 := RawSyscall(SYS_PIPE2, uintptr(unsafe.Pointer(p)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func mmap2(addr uintptr, length uintptr, prot int, flags int, fd int, pageOffset uintptr) (xaddr uintptr, err error) { + r0, _, e1 := Syscall6(SYS_MMAP2, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flags), uintptr(fd), uintptr(pageOffset)) + xaddr = uintptr(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func getrlimit(resource int, rlim *rlimit32) (err error) { + _, _, e1 := RawSyscall(SYS_GETRLIMIT, uintptr(resource), uintptr(unsafe.Pointer(rlim)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func setrlimit(resource int, rlim *rlimit32) (err error) { + _, _, e1 := RawSyscall(SYS_SETRLIMIT, uintptr(resource), uintptr(unsafe.Pointer(rlim)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func poll(fds *PollFd, nfds int, timeout int) (n int, err error) { + r0, _, e1 := Syscall(SYS_POLL, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(timeout)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux_mips64.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_mips64.go index ba55509..bf6f360 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux_mips64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_mips64.go @@ -572,6 +572,17 @@ func Getrusage(who int, rusage *Rusage) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Getsid(pid int) (sid int, err error) { + r0, _, e1 := RawSyscall(SYS_GETSID, uintptr(pid), 0, 0) + sid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Gettid() (tid int) { r0, _, _ := RawSyscall(SYS_GETTID, 0, 0, 0) tid = int(r0) @@ -762,8 +773,8 @@ func PivotRoot(newroot string, putold string) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func prlimit(pid int, resource int, old *Rlimit, newlimit *Rlimit) (err error) { - _, _, e1 := RawSyscall6(SYS_PRLIMIT64, uintptr(pid), uintptr(resource), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(newlimit)), 0, 0) +func prlimit(pid int, resource int, newlimit *Rlimit, old *Rlimit) (err error) { + _, _, e1 := RawSyscall6(SYS_PRLIMIT64, uintptr(pid), uintptr(resource), uintptr(unsafe.Pointer(newlimit)), uintptr(unsafe.Pointer(old)), 0, 0) if e1 != 0 { err = errnoErr(e1) } diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux_mips64le.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_mips64le.go index 2b1cc84..8c86bd7 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux_mips64le.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_mips64le.go @@ -572,6 +572,17 @@ func Getrusage(who int, rusage *Rusage) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Getsid(pid int) (sid int, err error) { + r0, _, e1 := RawSyscall(SYS_GETSID, uintptr(pid), 0, 0) + sid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Gettid() (tid int) { r0, _, _ := RawSyscall(SYS_GETTID, 0, 0, 0) tid = int(r0) @@ -762,8 +773,8 @@ func PivotRoot(newroot string, putold string) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func prlimit(pid int, resource int, old *Rlimit, newlimit *Rlimit) (err error) { - _, _, e1 := RawSyscall6(SYS_PRLIMIT64, uintptr(pid), uintptr(resource), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(newlimit)), 0, 0) +func prlimit(pid int, resource int, newlimit *Rlimit, old *Rlimit) (err error) { + _, _, e1 := RawSyscall6(SYS_PRLIMIT64, uintptr(pid), uintptr(resource), uintptr(unsafe.Pointer(newlimit)), uintptr(unsafe.Pointer(old)), 0, 0) if e1 != 0 { err = errnoErr(e1) } diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux_mipsle.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_mipsle.go new file mode 100644 index 0000000..645e00e --- /dev/null +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_mipsle.go @@ -0,0 +1,1829 @@ +// mksyscall.pl -l32 -arm syscall_linux.go syscall_linux_mipsx.go +// MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT + +// +build mipsle,linux + +package unix + +import ( + "syscall" + "unsafe" +) + +var _ syscall.Errno + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Linkat(olddirfd int, oldpath string, newdirfd int, newpath string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(oldpath) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(newpath) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_LINKAT, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), uintptr(flags), 0) + use(unsafe.Pointer(_p0)) + use(unsafe.Pointer(_p1)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func openat(dirfd int, path string, flags int, mode uint32) (fd int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_OPENAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags), uintptr(mode), 0, 0) + use(unsafe.Pointer(_p0)) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func ppoll(fds *PollFd, nfds int, timeout *Timespec, sigmask *Sigset_t) (n int, err error) { + r0, _, e1 := Syscall6(SYS_PPOLL, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(unsafe.Pointer(timeout)), uintptr(unsafe.Pointer(sigmask)), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Readlinkat(dirfd int, path string, buf []byte) (n int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 unsafe.Pointer + if len(buf) > 0 { + _p1 = unsafe.Pointer(&buf[0]) + } else { + _p1 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_READLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf)), 0, 0) + use(unsafe.Pointer(_p0)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Symlinkat(oldpath string, newdirfd int, newpath string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(oldpath) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(newpath) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_SYMLINKAT, uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1))) + use(unsafe.Pointer(_p0)) + use(unsafe.Pointer(_p1)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Unlinkat(dirfd int, path string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_UNLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags)) + use(unsafe.Pointer(_p0)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func utimes(path string, times *[2]Timeval) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), 0) + use(unsafe.Pointer(_p0)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_UTIMENSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), uintptr(flags), 0, 0) + use(unsafe.Pointer(_p0)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func futimesat(dirfd int, path *byte, times *[2]Timeval) (err error) { + _, _, e1 := Syscall(SYS_FUTIMESAT, uintptr(dirfd), uintptr(unsafe.Pointer(path)), uintptr(unsafe.Pointer(times))) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Getcwd(buf []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall(SYS_GETCWD, uintptr(_p0), uintptr(len(buf)), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) { + r0, _, e1 := Syscall6(SYS_WAIT4, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0) + wpid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func ptrace(request int, pid int, addr uintptr, data uintptr) (err error) { + _, _, e1 := Syscall6(SYS_PTRACE, uintptr(request), uintptr(pid), uintptr(addr), uintptr(data), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func reboot(magic1 uint, magic2 uint, cmd int, arg string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(arg) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_REBOOT, uintptr(magic1), uintptr(magic2), uintptr(cmd), uintptr(unsafe.Pointer(_p0)), 0, 0) + use(unsafe.Pointer(_p0)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func mount(source string, target string, fstype string, flags uintptr, data *byte) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(source) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(target) + if err != nil { + return + } + var _p2 *byte + _p2, err = BytePtrFromString(fstype) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_MOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(unsafe.Pointer(_p2)), uintptr(flags), uintptr(unsafe.Pointer(data)), 0) + use(unsafe.Pointer(_p0)) + use(unsafe.Pointer(_p1)) + use(unsafe.Pointer(_p2)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Acct(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_ACCT, uintptr(unsafe.Pointer(_p0)), 0, 0) + use(unsafe.Pointer(_p0)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Adjtimex(buf *Timex) (state int, err error) { + r0, _, e1 := Syscall(SYS_ADJTIMEX, uintptr(unsafe.Pointer(buf)), 0, 0) + state = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Chdir(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_CHDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) + use(unsafe.Pointer(_p0)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Chroot(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) + use(unsafe.Pointer(_p0)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func ClockGettime(clockid int32, time *Timespec) (err error) { + _, _, e1 := Syscall(SYS_CLOCK_GETTIME, uintptr(clockid), uintptr(unsafe.Pointer(time)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Close(fd int) (err error) { + _, _, e1 := Syscall(SYS_CLOSE, uintptr(fd), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Dup(oldfd int) (fd int, err error) { + r0, _, e1 := Syscall(SYS_DUP, uintptr(oldfd), 0, 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Dup3(oldfd int, newfd int, flags int) (err error) { + _, _, e1 := Syscall(SYS_DUP3, uintptr(oldfd), uintptr(newfd), uintptr(flags)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func EpollCreate(size int) (fd int, err error) { + r0, _, e1 := RawSyscall(SYS_EPOLL_CREATE, uintptr(size), 0, 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func EpollCreate1(flag int) (fd int, err error) { + r0, _, e1 := RawSyscall(SYS_EPOLL_CREATE1, uintptr(flag), 0, 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func EpollCtl(epfd int, op int, fd int, event *EpollEvent) (err error) { + _, _, e1 := RawSyscall6(SYS_EPOLL_CTL, uintptr(epfd), uintptr(op), uintptr(fd), uintptr(unsafe.Pointer(event)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Exit(code int) { + Syscall(SYS_EXIT_GROUP, uintptr(code), 0, 0) + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_FACCESSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) + use(unsafe.Pointer(_p0)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Fallocate(fd int, mode uint32, off int64, len int64) (err error) { + _, _, e1 := Syscall6(SYS_FALLOCATE, uintptr(fd), uintptr(mode), uintptr(off), uintptr(off>>32), uintptr(len), uintptr(len>>32)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Fchdir(fd int) (err error) { + _, _, e1 := Syscall(SYS_FCHDIR, uintptr(fd), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Fchmod(fd int, mode uint32) (err error) { + _, _, e1 := Syscall(SYS_FCHMOD, uintptr(fd), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_FCHMODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) + use(unsafe.Pointer(_p0)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_FCHOWNAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid), uintptr(flags), 0) + use(unsafe.Pointer(_p0)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func fcntl(fd int, cmd int, arg int) (val int, err error) { + r0, _, e1 := Syscall(SYS_FCNTL, uintptr(fd), uintptr(cmd), uintptr(arg)) + val = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Fdatasync(fd int) (err error) { + _, _, e1 := Syscall(SYS_FDATASYNC, uintptr(fd), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Flock(fd int, how int) (err error) { + _, _, e1 := Syscall(SYS_FLOCK, uintptr(fd), uintptr(how), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Fsync(fd int) (err error) { + _, _, e1 := Syscall(SYS_FSYNC, uintptr(fd), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Getdents(fd int, buf []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall(SYS_GETDENTS64, uintptr(fd), uintptr(_p0), uintptr(len(buf))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Getpgid(pid int) (pgid int, err error) { + r0, _, e1 := RawSyscall(SYS_GETPGID, uintptr(pid), 0, 0) + pgid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Getpid() (pid int) { + r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0) + pid = int(r0) + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Getppid() (ppid int) { + r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0) + ppid = int(r0) + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Getpriority(which int, who int) (prio int, err error) { + r0, _, e1 := Syscall(SYS_GETPRIORITY, uintptr(which), uintptr(who), 0) + prio = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Getrusage(who int, rusage *Rusage) (err error) { + _, _, e1 := RawSyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Getsid(pid int) (sid int, err error) { + r0, _, e1 := RawSyscall(SYS_GETSID, uintptr(pid), 0, 0) + sid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Gettid() (tid int) { + r0, _, _ := RawSyscall(SYS_GETTID, 0, 0, 0) + tid = int(r0) + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Getxattr(path string, attr string, dest []byte) (sz int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attr) + if err != nil { + return + } + var _p2 unsafe.Pointer + if len(dest) > 0 { + _p2 = unsafe.Pointer(&dest[0]) + } else { + _p2 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_GETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(dest)), 0, 0) + use(unsafe.Pointer(_p0)) + use(unsafe.Pointer(_p1)) + sz = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func InotifyAddWatch(fd int, pathname string, mask uint32) (watchdesc int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(pathname) + if err != nil { + return + } + r0, _, e1 := Syscall(SYS_INOTIFY_ADD_WATCH, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(mask)) + use(unsafe.Pointer(_p0)) + watchdesc = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func InotifyInit1(flags int) (fd int, err error) { + r0, _, e1 := RawSyscall(SYS_INOTIFY_INIT1, uintptr(flags), 0, 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func InotifyRmWatch(fd int, watchdesc uint32) (success int, err error) { + r0, _, e1 := RawSyscall(SYS_INOTIFY_RM_WATCH, uintptr(fd), uintptr(watchdesc), 0) + success = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Kill(pid int, sig syscall.Signal) (err error) { + _, _, e1 := RawSyscall(SYS_KILL, uintptr(pid), uintptr(sig), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Klogctl(typ int, buf []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall(SYS_SYSLOG, uintptr(typ), uintptr(_p0), uintptr(len(buf))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Listxattr(path string, dest []byte) (sz int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 unsafe.Pointer + if len(dest) > 0 { + _p1 = unsafe.Pointer(&dest[0]) + } else { + _p1 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall(SYS_LISTXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(dest))) + use(unsafe.Pointer(_p0)) + sz = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Mkdirat(dirfd int, path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_MKDIRAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) + use(unsafe.Pointer(_p0)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Mknodat(dirfd int, path string, mode uint32, dev int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_MKNODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev), 0, 0) + use(unsafe.Pointer(_p0)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Nanosleep(time *Timespec, leftover *Timespec) (err error) { + _, _, e1 := Syscall(SYS_NANOSLEEP, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func PivotRoot(newroot string, putold string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(newroot) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(putold) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_PIVOT_ROOT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) + use(unsafe.Pointer(_p0)) + use(unsafe.Pointer(_p1)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func prlimit(pid int, resource int, newlimit *Rlimit, old *Rlimit) (err error) { + _, _, e1 := RawSyscall6(SYS_PRLIMIT64, uintptr(pid), uintptr(resource), uintptr(unsafe.Pointer(newlimit)), uintptr(unsafe.Pointer(old)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Prctl(option int, arg2 uintptr, arg3 uintptr, arg4 uintptr, arg5 uintptr) (err error) { + _, _, e1 := Syscall6(SYS_PRCTL, uintptr(option), uintptr(arg2), uintptr(arg3), uintptr(arg4), uintptr(arg5), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func read(fd int, p []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(_p0), uintptr(len(p))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Removexattr(path string, attr string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attr) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_REMOVEXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) + use(unsafe.Pointer(_p0)) + use(unsafe.Pointer(_p1)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(oldpath) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(newpath) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_RENAMEAT, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), 0, 0) + use(unsafe.Pointer(_p0)) + use(unsafe.Pointer(_p1)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Setdomainname(p []byte) (err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_SETDOMAINNAME, uintptr(_p0), uintptr(len(p)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Sethostname(p []byte) (err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_SETHOSTNAME, uintptr(_p0), uintptr(len(p)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Setpgid(pid int, pgid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETPGID, uintptr(pid), uintptr(pgid), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Setsid() (pid int, err error) { + r0, _, e1 := RawSyscall(SYS_SETSID, 0, 0, 0) + pid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Settimeofday(tv *Timeval) (err error) { + _, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Setns(fd int, nstype int) (err error) { + _, _, e1 := Syscall(SYS_SETNS, uintptr(fd), uintptr(nstype), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Setpriority(which int, who int, prio int) (err error) { + _, _, e1 := Syscall(SYS_SETPRIORITY, uintptr(which), uintptr(who), uintptr(prio)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Setxattr(path string, attr string, data []byte, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attr) + if err != nil { + return + } + var _p2 unsafe.Pointer + if len(data) > 0 { + _p2 = unsafe.Pointer(&data[0]) + } else { + _p2 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall6(SYS_SETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(data)), uintptr(flags), 0) + use(unsafe.Pointer(_p0)) + use(unsafe.Pointer(_p1)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Sync() { + Syscall(SYS_SYNC, 0, 0, 0) + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Sysinfo(info *Sysinfo_t) (err error) { + _, _, e1 := RawSyscall(SYS_SYSINFO, uintptr(unsafe.Pointer(info)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Tee(rfd int, wfd int, len int, flags int) (n int64, err error) { + r0, r1, e1 := Syscall6(SYS_TEE, uintptr(rfd), uintptr(wfd), uintptr(len), uintptr(flags), 0, 0) + n = int64(int64(r1)<<32 | int64(r0)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Tgkill(tgid int, tid int, sig syscall.Signal) (err error) { + _, _, e1 := RawSyscall(SYS_TGKILL, uintptr(tgid), uintptr(tid), uintptr(sig)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Times(tms *Tms) (ticks uintptr, err error) { + r0, _, e1 := RawSyscall(SYS_TIMES, uintptr(unsafe.Pointer(tms)), 0, 0) + ticks = uintptr(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Umask(mask int) (oldmask int) { + r0, _, _ := RawSyscall(SYS_UMASK, uintptr(mask), 0, 0) + oldmask = int(r0) + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Uname(buf *Utsname) (err error) { + _, _, e1 := RawSyscall(SYS_UNAME, uintptr(unsafe.Pointer(buf)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Unmount(target string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(target) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_UMOUNT2, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) + use(unsafe.Pointer(_p0)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Unshare(flags int) (err error) { + _, _, e1 := Syscall(SYS_UNSHARE, uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Ustat(dev int, ubuf *Ustat_t) (err error) { + _, _, e1 := Syscall(SYS_USTAT, uintptr(dev), uintptr(unsafe.Pointer(ubuf)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func write(fd int, p []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(_p0), uintptr(len(p))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func exitThread(code int) (err error) { + _, _, e1 := Syscall(SYS_EXIT, uintptr(code), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func readlen(fd int, p *byte, np int) (n int, err error) { + r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(p)), uintptr(np)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func writelen(fd int, p *byte, np int) (n int, err error) { + r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(unsafe.Pointer(p)), uintptr(np)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func munmap(addr uintptr, length uintptr) (err error) { + _, _, e1 := Syscall(SYS_MUNMAP, uintptr(addr), uintptr(length), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Madvise(b []byte, advice int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MADVISE, uintptr(_p0), uintptr(len(b)), uintptr(advice)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Mprotect(b []byte, prot int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Mlock(b []byte) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Munlock(b []byte) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Mlockall(flags int) (err error) { + _, _, e1 := Syscall(SYS_MLOCKALL, uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Munlockall() (err error) { + _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Dup2(oldfd int, newfd int) (err error) { + _, _, e1 := Syscall(SYS_DUP2, uintptr(oldfd), uintptr(newfd), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Fchown(fd int, uid int, gid int) (err error) { + _, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Ftruncate(fd int, length int64) (err error) { + _, _, e1 := Syscall6(SYS_FTRUNCATE64, uintptr(fd), 0, uintptr(length), uintptr(length>>32), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Getegid() (egid int) { + r0, _, _ := RawSyscall(SYS_GETEGID, 0, 0, 0) + egid = int(r0) + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Geteuid() (euid int) { + r0, _, _ := RawSyscall(SYS_GETEUID, 0, 0, 0) + euid = int(r0) + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Getgid() (gid int) { + r0, _, _ := RawSyscall(SYS_GETGID, 0, 0, 0) + gid = int(r0) + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Getuid() (uid int) { + r0, _, _ := RawSyscall(SYS_GETUID, 0, 0, 0) + uid = int(r0) + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Lchown(path string, uid int, gid int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_LCHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) + use(unsafe.Pointer(_p0)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Listen(s int, n int) (err error) { + _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(n), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Pread(fd int, p []byte, offset int64) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_PREAD64, uintptr(fd), uintptr(_p0), uintptr(len(p)), 0, uintptr(offset), uintptr(offset>>32)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Pwrite(fd int, p []byte, offset int64) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_PWRITE64, uintptr(fd), uintptr(_p0), uintptr(len(p)), 0, uintptr(offset), uintptr(offset>>32)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) { + r0, _, e1 := Syscall6(SYS__NEWSELECT, uintptr(nfd), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) { + r0, _, e1 := Syscall6(SYS_SENDFILE64, uintptr(outfd), uintptr(infd), uintptr(unsafe.Pointer(offset)), uintptr(count), 0, 0) + written = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Setfsgid(gid int) (err error) { + _, _, e1 := Syscall(SYS_SETFSGID, uintptr(gid), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Setfsuid(uid int) (err error) { + _, _, e1 := Syscall(SYS_SETFSUID, uintptr(uid), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Setregid(rgid int, egid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETREGID, uintptr(rgid), uintptr(egid), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Setresgid(rgid int, egid int, sgid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETRESGID, uintptr(rgid), uintptr(egid), uintptr(sgid)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Setresuid(ruid int, euid int, suid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETRESUID, uintptr(ruid), uintptr(euid), uintptr(suid)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Setreuid(ruid int, euid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETREUID, uintptr(ruid), uintptr(euid), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Shutdown(fd int, how int) (err error) { + _, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(fd), uintptr(how), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int64, err error) { + r0, r1, e1 := Syscall6(SYS_SPLICE, uintptr(rfd), uintptr(unsafe.Pointer(roff)), uintptr(wfd), uintptr(unsafe.Pointer(woff)), uintptr(len), uintptr(flags)) + n = int64(int64(r1)<<32 | int64(r0)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func SyncFileRange(fd int, off int64, n int64, flags int) (err error) { + _, _, e1 := Syscall9(SYS_SYNC_FILE_RANGE, uintptr(fd), 0, uintptr(off), uintptr(off>>32), uintptr(n), uintptr(n>>32), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Truncate(path string, length int64) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_TRUNCATE64, uintptr(unsafe.Pointer(_p0)), 0, uintptr(length), uintptr(length>>32), 0, 0) + use(unsafe.Pointer(_p0)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) { + r0, _, e1 := Syscall(SYS_ACCEPT, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func accept4(s int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (fd int, err error) { + r0, _, e1 := Syscall6(SYS_ACCEPT4, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), uintptr(flags), 0, 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { + _, _, e1 := Syscall(SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { + _, _, e1 := Syscall(SYS_CONNECT, uintptr(s), uintptr(addr), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func getgroups(n int, list *_Gid_t) (nn int, err error) { + r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(n), uintptr(unsafe.Pointer(list)), 0) + nn = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func setgroups(n int, list *_Gid_t) (err error) { + _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(n), uintptr(unsafe.Pointer(list)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { + _, _, e1 := Syscall6(SYS_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { + _, _, e1 := Syscall6(SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func socket(domain int, typ int, proto int) (fd int, err error) { + r0, _, e1 := RawSyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto)) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { + _, _, e1 := RawSyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { + _, _, e1 := RawSyscall(SYS_GETPEERNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { + _, _, e1 := RawSyscall(SYS_GETSOCKNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_RECVFROM, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall6(SYS_SENDTO, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { + r0, _, e1 := Syscall(SYS_RECVMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { + r0, _, e1 := Syscall(SYS_SENDMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func InotifyInit() (fd int, err error) { + r0, _, e1 := RawSyscall(SYS_INOTIFY_INIT, 0, 0, 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Ioperm(from int, num int, on int) (err error) { + _, _, e1 := Syscall(SYS_IOPERM, uintptr(from), uintptr(num), uintptr(on)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Iopl(level int) (err error) { + _, _, e1 := Syscall(SYS_IOPL, uintptr(level), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Gettimeofday(tv *Timeval) (err error) { + _, _, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Time(t *Time_t) (tt Time_t, err error) { + r0, _, e1 := RawSyscall(SYS_TIME, uintptr(unsafe.Pointer(t)), 0, 0) + tt = Time_t(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Lstat(path string, stat *Stat_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_LSTAT64, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) + use(unsafe.Pointer(_p0)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Fstat(fd int, stat *Stat_t) (err error) { + _, _, e1 := Syscall(SYS_FSTAT64, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Stat(path string, stat *Stat_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_STAT64, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) + use(unsafe.Pointer(_p0)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Utime(path string, buf *Utimbuf) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_UTIME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(buf)), 0) + use(unsafe.Pointer(_p0)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) { + var _p0 unsafe.Pointer + if len(events) > 0 { + _p0 = unsafe.Pointer(&events[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_EPOLL_WAIT, uintptr(epfd), uintptr(_p0), uintptr(len(events)), uintptr(msec), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Pause() (err error) { + _, _, e1 := Syscall(SYS_PAUSE, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func pipe2(p *[2]_C_int, flags int) (err error) { + _, _, e1 := RawSyscall(SYS_PIPE2, uintptr(unsafe.Pointer(p)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func mmap2(addr uintptr, length uintptr, prot int, flags int, fd int, pageOffset uintptr) (xaddr uintptr, err error) { + r0, _, e1 := Syscall6(SYS_MMAP2, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flags), uintptr(fd), uintptr(pageOffset)) + xaddr = uintptr(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func getrlimit(resource int, rlim *rlimit32) (err error) { + _, _, e1 := RawSyscall(SYS_GETRLIMIT, uintptr(resource), uintptr(unsafe.Pointer(rlim)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func setrlimit(resource int, rlim *rlimit32) (err error) { + _, _, e1 := RawSyscall(SYS_SETRLIMIT, uintptr(resource), uintptr(unsafe.Pointer(rlim)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func poll(fds *PollFd, nfds int, timeout int) (n int, err error) { + r0, _, e1 := Syscall(SYS_POLL, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(timeout)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux_ppc64.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_ppc64.go index 25f39db..f5d488b 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux_ppc64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_ppc64.go @@ -572,6 +572,17 @@ func Getrusage(who int, rusage *Rusage) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Getsid(pid int) (sid int, err error) { + r0, _, e1 := RawSyscall(SYS_GETSID, uintptr(pid), 0, 0) + sid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Gettid() (tid int) { r0, _, _ := RawSyscall(SYS_GETTID, 0, 0, 0) tid = int(r0) @@ -762,8 +773,8 @@ func PivotRoot(newroot string, putold string) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func prlimit(pid int, resource int, old *Rlimit, newlimit *Rlimit) (err error) { - _, _, e1 := RawSyscall6(SYS_PRLIMIT64, uintptr(pid), uintptr(resource), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(newlimit)), 0, 0) +func prlimit(pid int, resource int, newlimit *Rlimit, old *Rlimit) (err error) { + _, _, e1 := RawSyscall6(SYS_PRLIMIT64, uintptr(pid), uintptr(resource), uintptr(unsafe.Pointer(newlimit)), uintptr(unsafe.Pointer(old)), 0, 0) if e1 != 0 { err = errnoErr(e1) } diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux_ppc64le.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_ppc64le.go index 70702b5..5183711 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux_ppc64le.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_ppc64le.go @@ -572,6 +572,17 @@ func Getrusage(who int, rusage *Rusage) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Getsid(pid int) (sid int, err error) { + r0, _, e1 := RawSyscall(SYS_GETSID, uintptr(pid), 0, 0) + sid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Gettid() (tid int) { r0, _, _ := RawSyscall(SYS_GETTID, 0, 0, 0) tid = int(r0) @@ -762,8 +773,8 @@ func PivotRoot(newroot string, putold string) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func prlimit(pid int, resource int, old *Rlimit, newlimit *Rlimit) (err error) { - _, _, e1 := RawSyscall6(SYS_PRLIMIT64, uintptr(pid), uintptr(resource), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(newlimit)), 0, 0) +func prlimit(pid int, resource int, newlimit *Rlimit, old *Rlimit) (err error) { + _, _, e1 := RawSyscall6(SYS_PRLIMIT64, uintptr(pid), uintptr(resource), uintptr(unsafe.Pointer(newlimit)), uintptr(unsafe.Pointer(old)), 0, 0) if e1 != 0 { err = errnoErr(e1) } diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux_s390x.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_s390x.go index dbaa53b..4c7ed08 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux_s390x.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_s390x.go @@ -64,7 +64,7 @@ func ppoll(fds *PollFd, nfds int, timeout *Timespec, sigmask *Sigset_t) (n int, // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func readlinkat(dirfd int, path string, buf []byte) (n int, err error) { +func Readlinkat(dirfd int, path string, buf []byte) (n int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { @@ -87,7 +87,7 @@ func readlinkat(dirfd int, path string, buf []byte) (n int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func symlinkat(oldpath string, newdirfd int, newpath string) (err error) { +func Symlinkat(oldpath string, newdirfd int, newpath string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(oldpath) if err != nil { @@ -109,7 +109,7 @@ func symlinkat(oldpath string, newdirfd int, newpath string) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func unlinkat(dirfd int, path string, flags int) (err error) { +func Unlinkat(dirfd int, path string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { @@ -572,6 +572,17 @@ func Getrusage(who int, rusage *Rusage) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Getsid(pid int) (sid int, err error) { + r0, _, e1 := RawSyscall(SYS_GETSID, uintptr(pid), 0, 0) + sid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Gettid() (tid int) { r0, _, _ := RawSyscall(SYS_GETTID, 0, 0, 0) tid = int(r0) @@ -762,8 +773,8 @@ func PivotRoot(newroot string, putold string) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func prlimit(pid int, resource int, old *Rlimit, newlimit *Rlimit) (err error) { - _, _, e1 := RawSyscall6(SYS_PRLIMIT64, uintptr(pid), uintptr(resource), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(newlimit)), 0, 0) +func prlimit(pid int, resource int, newlimit *Rlimit, old *Rlimit) (err error) { + _, _, e1 := RawSyscall6(SYS_PRLIMIT64, uintptr(pid), uintptr(resource), uintptr(unsafe.Pointer(newlimit)), uintptr(unsafe.Pointer(old)), 0, 0) if e1 != 0 { err = errnoErr(e1) } diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux_sparc64.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_sparc64.go index 08ee5d0..beb83e4 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux_sparc64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_sparc64.go @@ -64,7 +64,7 @@ func ppoll(fds *PollFd, nfds int, timeout *Timespec, sigmask *Sigset_t) (n int, // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func readlinkat(dirfd int, path string, buf []byte) (n int, err error) { +func Readlinkat(dirfd int, path string, buf []byte) (n int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { @@ -87,7 +87,7 @@ func readlinkat(dirfd int, path string, buf []byte) (n int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func symlinkat(oldpath string, newdirfd int, newpath string) (err error) { +func Symlinkat(oldpath string, newdirfd int, newpath string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(oldpath) if err != nil { @@ -109,7 +109,7 @@ func symlinkat(oldpath string, newdirfd int, newpath string) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func unlinkat(dirfd int, path string, flags int) (err error) { +func Unlinkat(dirfd int, path string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { @@ -572,6 +572,17 @@ func Getrusage(who int, rusage *Rusage) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Getsid(pid int) (sid int, err error) { + r0, _, e1 := RawSyscall(SYS_GETSID, uintptr(pid), 0, 0) + sid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Gettid() (tid int) { r0, _, _ := RawSyscall(SYS_GETTID, 0, 0, 0) tid = int(r0) @@ -762,8 +773,8 @@ func PivotRoot(newroot string, putold string) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func prlimit(pid int, resource int, old *Rlimit, newlimit *Rlimit) (err error) { - _, _, e1 := RawSyscall6(SYS_PRLIMIT64, uintptr(pid), uintptr(resource), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(newlimit)), 0, 0) +func prlimit(pid int, resource int, newlimit *Rlimit, old *Rlimit) (err error) { + _, _, e1 := RawSyscall6(SYS_PRLIMIT64, uintptr(pid), uintptr(resource), uintptr(unsafe.Pointer(newlimit)), uintptr(unsafe.Pointer(old)), 0, 0) if e1 != 0 { err = errnoErr(e1) } diff --git a/vendor/golang.org/x/sys/unix/zsysnum_linux_mips.go b/vendor/golang.org/x/sys/unix/zsysnum_linux_mips.go new file mode 100644 index 0000000..0786867 --- /dev/null +++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_mips.go @@ -0,0 +1,359 @@ +// mksysnum_linux.pl /usr/include/mips-linux-gnu/asm/unistd.h +// MACHINE GENERATED BY THE ABOVE COMMAND; DO NOT EDIT + +// +build mips,linux + +package unix + +const ( + SYS_SYSCALL = 4000 + SYS_EXIT = 4001 + SYS_FORK = 4002 + SYS_READ = 4003 + SYS_WRITE = 4004 + SYS_OPEN = 4005 + SYS_CLOSE = 4006 + SYS_WAITPID = 4007 + SYS_CREAT = 4008 + SYS_LINK = 4009 + SYS_UNLINK = 4010 + SYS_EXECVE = 4011 + SYS_CHDIR = 4012 + SYS_TIME = 4013 + SYS_MKNOD = 4014 + SYS_CHMOD = 4015 + SYS_LCHOWN = 4016 + SYS_BREAK = 4017 + SYS_UNUSED18 = 4018 + SYS_LSEEK = 4019 + SYS_GETPID = 4020 + SYS_MOUNT = 4021 + SYS_UMOUNT = 4022 + SYS_SETUID = 4023 + SYS_GETUID = 4024 + SYS_STIME = 4025 + SYS_PTRACE = 4026 + SYS_ALARM = 4027 + SYS_UNUSED28 = 4028 + SYS_PAUSE = 4029 + SYS_UTIME = 4030 + SYS_STTY = 4031 + SYS_GTTY = 4032 + SYS_ACCESS = 4033 + SYS_NICE = 4034 + SYS_FTIME = 4035 + SYS_SYNC = 4036 + SYS_KILL = 4037 + SYS_RENAME = 4038 + SYS_MKDIR = 4039 + SYS_RMDIR = 4040 + SYS_DUP = 4041 + SYS_PIPE = 4042 + SYS_TIMES = 4043 + SYS_PROF = 4044 + SYS_BRK = 4045 + SYS_SETGID = 4046 + SYS_GETGID = 4047 + SYS_SIGNAL = 4048 + SYS_GETEUID = 4049 + SYS_GETEGID = 4050 + SYS_ACCT = 4051 + SYS_UMOUNT2 = 4052 + SYS_LOCK = 4053 + SYS_IOCTL = 4054 + SYS_FCNTL = 4055 + SYS_MPX = 4056 + SYS_SETPGID = 4057 + SYS_ULIMIT = 4058 + SYS_UNUSED59 = 4059 + SYS_UMASK = 4060 + SYS_CHROOT = 4061 + SYS_USTAT = 4062 + SYS_DUP2 = 4063 + SYS_GETPPID = 4064 + SYS_GETPGRP = 4065 + SYS_SETSID = 4066 + SYS_SIGACTION = 4067 + SYS_SGETMASK = 4068 + SYS_SSETMASK = 4069 + SYS_SETREUID = 4070 + SYS_SETREGID = 4071 + SYS_SIGSUSPEND = 4072 + SYS_SIGPENDING = 4073 + SYS_SETHOSTNAME = 4074 + SYS_SETRLIMIT = 4075 + SYS_GETRLIMIT = 4076 + SYS_GETRUSAGE = 4077 + SYS_GETTIMEOFDAY = 4078 + SYS_SETTIMEOFDAY = 4079 + SYS_GETGROUPS = 4080 + SYS_SETGROUPS = 4081 + SYS_RESERVED82 = 4082 + SYS_SYMLINK = 4083 + SYS_UNUSED84 = 4084 + SYS_READLINK = 4085 + SYS_USELIB = 4086 + SYS_SWAPON = 4087 + SYS_REBOOT = 4088 + SYS_READDIR = 4089 + SYS_MMAP = 4090 + SYS_MUNMAP = 4091 + SYS_TRUNCATE = 4092 + SYS_FTRUNCATE = 4093 + SYS_FCHMOD = 4094 + SYS_FCHOWN = 4095 + SYS_GETPRIORITY = 4096 + SYS_SETPRIORITY = 4097 + SYS_PROFIL = 4098 + SYS_STATFS = 4099 + SYS_FSTATFS = 4100 + SYS_IOPERM = 4101 + SYS_SOCKETCALL = 4102 + SYS_SYSLOG = 4103 + SYS_SETITIMER = 4104 + SYS_GETITIMER = 4105 + SYS_STAT = 4106 + SYS_LSTAT = 4107 + SYS_FSTAT = 4108 + SYS_UNUSED109 = 4109 + SYS_IOPL = 4110 + SYS_VHANGUP = 4111 + SYS_IDLE = 4112 + SYS_VM86 = 4113 + SYS_WAIT4 = 4114 + SYS_SWAPOFF = 4115 + SYS_SYSINFO = 4116 + SYS_IPC = 4117 + SYS_FSYNC = 4118 + SYS_SIGRETURN = 4119 + SYS_CLONE = 4120 + SYS_SETDOMAINNAME = 4121 + SYS_UNAME = 4122 + SYS_MODIFY_LDT = 4123 + SYS_ADJTIMEX = 4124 + SYS_MPROTECT = 4125 + SYS_SIGPROCMASK = 4126 + SYS_CREATE_MODULE = 4127 + SYS_INIT_MODULE = 4128 + SYS_DELETE_MODULE = 4129 + SYS_GET_KERNEL_SYMS = 4130 + SYS_QUOTACTL = 4131 + SYS_GETPGID = 4132 + SYS_FCHDIR = 4133 + SYS_BDFLUSH = 4134 + SYS_SYSFS = 4135 + SYS_PERSONALITY = 4136 + SYS_AFS_SYSCALL = 4137 + SYS_SETFSUID = 4138 + SYS_SETFSGID = 4139 + SYS__LLSEEK = 4140 + SYS_GETDENTS = 4141 + SYS__NEWSELECT = 4142 + SYS_FLOCK = 4143 + SYS_MSYNC = 4144 + SYS_READV = 4145 + SYS_WRITEV = 4146 + SYS_CACHEFLUSH = 4147 + SYS_CACHECTL = 4148 + SYS_SYSMIPS = 4149 + SYS_UNUSED150 = 4150 + SYS_GETSID = 4151 + SYS_FDATASYNC = 4152 + SYS__SYSCTL = 4153 + SYS_MLOCK = 4154 + SYS_MUNLOCK = 4155 + SYS_MLOCKALL = 4156 + SYS_MUNLOCKALL = 4157 + SYS_SCHED_SETPARAM = 4158 + SYS_SCHED_GETPARAM = 4159 + SYS_SCHED_SETSCHEDULER = 4160 + SYS_SCHED_GETSCHEDULER = 4161 + SYS_SCHED_YIELD = 4162 + SYS_SCHED_GET_PRIORITY_MAX = 4163 + SYS_SCHED_GET_PRIORITY_MIN = 4164 + SYS_SCHED_RR_GET_INTERVAL = 4165 + SYS_NANOSLEEP = 4166 + SYS_MREMAP = 4167 + SYS_ACCEPT = 4168 + SYS_BIND = 4169 + SYS_CONNECT = 4170 + SYS_GETPEERNAME = 4171 + SYS_GETSOCKNAME = 4172 + SYS_GETSOCKOPT = 4173 + SYS_LISTEN = 4174 + SYS_RECV = 4175 + SYS_RECVFROM = 4176 + SYS_RECVMSG = 4177 + SYS_SEND = 4178 + SYS_SENDMSG = 4179 + SYS_SENDTO = 4180 + SYS_SETSOCKOPT = 4181 + SYS_SHUTDOWN = 4182 + SYS_SOCKET = 4183 + SYS_SOCKETPAIR = 4184 + SYS_SETRESUID = 4185 + SYS_GETRESUID = 4186 + SYS_QUERY_MODULE = 4187 + SYS_POLL = 4188 + SYS_NFSSERVCTL = 4189 + SYS_SETRESGID = 4190 + SYS_GETRESGID = 4191 + SYS_PRCTL = 4192 + SYS_RT_SIGRETURN = 4193 + SYS_RT_SIGACTION = 4194 + SYS_RT_SIGPROCMASK = 4195 + SYS_RT_SIGPENDING = 4196 + SYS_RT_SIGTIMEDWAIT = 4197 + SYS_RT_SIGQUEUEINFO = 4198 + SYS_RT_SIGSUSPEND = 4199 + SYS_PREAD64 = 4200 + SYS_PWRITE64 = 4201 + SYS_CHOWN = 4202 + SYS_GETCWD = 4203 + SYS_CAPGET = 4204 + SYS_CAPSET = 4205 + SYS_SIGALTSTACK = 4206 + SYS_SENDFILE = 4207 + SYS_GETPMSG = 4208 + SYS_PUTPMSG = 4209 + SYS_MMAP2 = 4210 + SYS_TRUNCATE64 = 4211 + SYS_FTRUNCATE64 = 4212 + SYS_STAT64 = 4213 + SYS_LSTAT64 = 4214 + SYS_FSTAT64 = 4215 + SYS_PIVOT_ROOT = 4216 + SYS_MINCORE = 4217 + SYS_MADVISE = 4218 + SYS_GETDENTS64 = 4219 + SYS_FCNTL64 = 4220 + SYS_RESERVED221 = 4221 + SYS_GETTID = 4222 + SYS_READAHEAD = 4223 + SYS_SETXATTR = 4224 + SYS_LSETXATTR = 4225 + SYS_FSETXATTR = 4226 + SYS_GETXATTR = 4227 + SYS_LGETXATTR = 4228 + SYS_FGETXATTR = 4229 + SYS_LISTXATTR = 4230 + SYS_LLISTXATTR = 4231 + SYS_FLISTXATTR = 4232 + SYS_REMOVEXATTR = 4233 + SYS_LREMOVEXATTR = 4234 + SYS_FREMOVEXATTR = 4235 + SYS_TKILL = 4236 + SYS_SENDFILE64 = 4237 + SYS_FUTEX = 4238 + SYS_SCHED_SETAFFINITY = 4239 + SYS_SCHED_GETAFFINITY = 4240 + SYS_IO_SETUP = 4241 + SYS_IO_DESTROY = 4242 + SYS_IO_GETEVENTS = 4243 + SYS_IO_SUBMIT = 4244 + SYS_IO_CANCEL = 4245 + SYS_EXIT_GROUP = 4246 + SYS_LOOKUP_DCOOKIE = 4247 + SYS_EPOLL_CREATE = 4248 + SYS_EPOLL_CTL = 4249 + SYS_EPOLL_WAIT = 4250 + SYS_REMAP_FILE_PAGES = 4251 + SYS_SET_TID_ADDRESS = 4252 + SYS_RESTART_SYSCALL = 4253 + SYS_FADVISE64 = 4254 + SYS_STATFS64 = 4255 + SYS_FSTATFS64 = 4256 + SYS_TIMER_CREATE = 4257 + SYS_TIMER_SETTIME = 4258 + SYS_TIMER_GETTIME = 4259 + SYS_TIMER_GETOVERRUN = 4260 + SYS_TIMER_DELETE = 4261 + SYS_CLOCK_SETTIME = 4262 + SYS_CLOCK_GETTIME = 4263 + SYS_CLOCK_GETRES = 4264 + SYS_CLOCK_NANOSLEEP = 4265 + SYS_TGKILL = 4266 + SYS_UTIMES = 4267 + SYS_MBIND = 4268 + SYS_GET_MEMPOLICY = 4269 + SYS_SET_MEMPOLICY = 4270 + SYS_MQ_OPEN = 4271 + SYS_MQ_UNLINK = 4272 + SYS_MQ_TIMEDSEND = 4273 + SYS_MQ_TIMEDRECEIVE = 4274 + SYS_MQ_NOTIFY = 4275 + SYS_MQ_GETSETATTR = 4276 + SYS_VSERVER = 4277 + SYS_WAITID = 4278 + SYS_ADD_KEY = 4280 + SYS_REQUEST_KEY = 4281 + SYS_KEYCTL = 4282 + SYS_SET_THREAD_AREA = 4283 + SYS_INOTIFY_INIT = 4284 + SYS_INOTIFY_ADD_WATCH = 4285 + SYS_INOTIFY_RM_WATCH = 4286 + SYS_MIGRATE_PAGES = 4287 + SYS_OPENAT = 4288 + SYS_MKDIRAT = 4289 + SYS_MKNODAT = 4290 + SYS_FCHOWNAT = 4291 + SYS_FUTIMESAT = 4292 + SYS_FSTATAT64 = 4293 + SYS_UNLINKAT = 4294 + SYS_RENAMEAT = 4295 + SYS_LINKAT = 4296 + SYS_SYMLINKAT = 4297 + SYS_READLINKAT = 4298 + SYS_FCHMODAT = 4299 + SYS_FACCESSAT = 4300 + SYS_PSELECT6 = 4301 + SYS_PPOLL = 4302 + SYS_UNSHARE = 4303 + SYS_SPLICE = 4304 + SYS_SYNC_FILE_RANGE = 4305 + SYS_TEE = 4306 + SYS_VMSPLICE = 4307 + SYS_MOVE_PAGES = 4308 + SYS_SET_ROBUST_LIST = 4309 + SYS_GET_ROBUST_LIST = 4310 + SYS_KEXEC_LOAD = 4311 + SYS_GETCPU = 4312 + SYS_EPOLL_PWAIT = 4313 + SYS_IOPRIO_SET = 4314 + SYS_IOPRIO_GET = 4315 + SYS_UTIMENSAT = 4316 + SYS_SIGNALFD = 4317 + SYS_TIMERFD = 4318 + SYS_EVENTFD = 4319 + SYS_FALLOCATE = 4320 + SYS_TIMERFD_CREATE = 4321 + SYS_TIMERFD_GETTIME = 4322 + SYS_TIMERFD_SETTIME = 4323 + SYS_SIGNALFD4 = 4324 + SYS_EVENTFD2 = 4325 + SYS_EPOLL_CREATE1 = 4326 + SYS_DUP3 = 4327 + SYS_PIPE2 = 4328 + SYS_INOTIFY_INIT1 = 4329 + SYS_PREADV = 4330 + SYS_PWRITEV = 4331 + SYS_RT_TGSIGQUEUEINFO = 4332 + SYS_PERF_EVENT_OPEN = 4333 + SYS_ACCEPT4 = 4334 + SYS_RECVMMSG = 4335 + SYS_FANOTIFY_INIT = 4336 + SYS_FANOTIFY_MARK = 4337 + SYS_PRLIMIT64 = 4338 + SYS_NAME_TO_HANDLE_AT = 4339 + SYS_OPEN_BY_HANDLE_AT = 4340 + SYS_CLOCK_ADJTIME = 4341 + SYS_SYNCFS = 4342 + SYS_SENDMMSG = 4343 + SYS_SETNS = 4344 + SYS_PROCESS_VM_READV = 4345 + SYS_PROCESS_VM_WRITEV = 4346 + SYS_LINUX_SYSCALLS = 4346 + SYS_O32_LINUX_SYSCALLS = 4346 + SYS_64_LINUX_SYSCALLS = 4305 + SYS_N32_LINUX_SYSCALLS = 4310 +) diff --git a/vendor/golang.org/x/sys/unix/zsysnum_linux_mipsle.go b/vendor/golang.org/x/sys/unix/zsysnum_linux_mipsle.go new file mode 100644 index 0000000..25d2317 --- /dev/null +++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_mipsle.go @@ -0,0 +1,359 @@ +// mksysnum_linux.pl /usr/include/mips-linux-gnu/asm/unistd.h +// MACHINE GENERATED BY THE ABOVE COMMAND; DO NOT EDIT + +// +build mipsle,linux + +package unix + +const ( + SYS_SYSCALL = 4000 + SYS_EXIT = 4001 + SYS_FORK = 4002 + SYS_READ = 4003 + SYS_WRITE = 4004 + SYS_OPEN = 4005 + SYS_CLOSE = 4006 + SYS_WAITPID = 4007 + SYS_CREAT = 4008 + SYS_LINK = 4009 + SYS_UNLINK = 4010 + SYS_EXECVE = 4011 + SYS_CHDIR = 4012 + SYS_TIME = 4013 + SYS_MKNOD = 4014 + SYS_CHMOD = 4015 + SYS_LCHOWN = 4016 + SYS_BREAK = 4017 + SYS_UNUSED18 = 4018 + SYS_LSEEK = 4019 + SYS_GETPID = 4020 + SYS_MOUNT = 4021 + SYS_UMOUNT = 4022 + SYS_SETUID = 4023 + SYS_GETUID = 4024 + SYS_STIME = 4025 + SYS_PTRACE = 4026 + SYS_ALARM = 4027 + SYS_UNUSED28 = 4028 + SYS_PAUSE = 4029 + SYS_UTIME = 4030 + SYS_STTY = 4031 + SYS_GTTY = 4032 + SYS_ACCESS = 4033 + SYS_NICE = 4034 + SYS_FTIME = 4035 + SYS_SYNC = 4036 + SYS_KILL = 4037 + SYS_RENAME = 4038 + SYS_MKDIR = 4039 + SYS_RMDIR = 4040 + SYS_DUP = 4041 + SYS_PIPE = 4042 + SYS_TIMES = 4043 + SYS_PROF = 4044 + SYS_BRK = 4045 + SYS_SETGID = 4046 + SYS_GETGID = 4047 + SYS_SIGNAL = 4048 + SYS_GETEUID = 4049 + SYS_GETEGID = 4050 + SYS_ACCT = 4051 + SYS_UMOUNT2 = 4052 + SYS_LOCK = 4053 + SYS_IOCTL = 4054 + SYS_FCNTL = 4055 + SYS_MPX = 4056 + SYS_SETPGID = 4057 + SYS_ULIMIT = 4058 + SYS_UNUSED59 = 4059 + SYS_UMASK = 4060 + SYS_CHROOT = 4061 + SYS_USTAT = 4062 + SYS_DUP2 = 4063 + SYS_GETPPID = 4064 + SYS_GETPGRP = 4065 + SYS_SETSID = 4066 + SYS_SIGACTION = 4067 + SYS_SGETMASK = 4068 + SYS_SSETMASK = 4069 + SYS_SETREUID = 4070 + SYS_SETREGID = 4071 + SYS_SIGSUSPEND = 4072 + SYS_SIGPENDING = 4073 + SYS_SETHOSTNAME = 4074 + SYS_SETRLIMIT = 4075 + SYS_GETRLIMIT = 4076 + SYS_GETRUSAGE = 4077 + SYS_GETTIMEOFDAY = 4078 + SYS_SETTIMEOFDAY = 4079 + SYS_GETGROUPS = 4080 + SYS_SETGROUPS = 4081 + SYS_RESERVED82 = 4082 + SYS_SYMLINK = 4083 + SYS_UNUSED84 = 4084 + SYS_READLINK = 4085 + SYS_USELIB = 4086 + SYS_SWAPON = 4087 + SYS_REBOOT = 4088 + SYS_READDIR = 4089 + SYS_MMAP = 4090 + SYS_MUNMAP = 4091 + SYS_TRUNCATE = 4092 + SYS_FTRUNCATE = 4093 + SYS_FCHMOD = 4094 + SYS_FCHOWN = 4095 + SYS_GETPRIORITY = 4096 + SYS_SETPRIORITY = 4097 + SYS_PROFIL = 4098 + SYS_STATFS = 4099 + SYS_FSTATFS = 4100 + SYS_IOPERM = 4101 + SYS_SOCKETCALL = 4102 + SYS_SYSLOG = 4103 + SYS_SETITIMER = 4104 + SYS_GETITIMER = 4105 + SYS_STAT = 4106 + SYS_LSTAT = 4107 + SYS_FSTAT = 4108 + SYS_UNUSED109 = 4109 + SYS_IOPL = 4110 + SYS_VHANGUP = 4111 + SYS_IDLE = 4112 + SYS_VM86 = 4113 + SYS_WAIT4 = 4114 + SYS_SWAPOFF = 4115 + SYS_SYSINFO = 4116 + SYS_IPC = 4117 + SYS_FSYNC = 4118 + SYS_SIGRETURN = 4119 + SYS_CLONE = 4120 + SYS_SETDOMAINNAME = 4121 + SYS_UNAME = 4122 + SYS_MODIFY_LDT = 4123 + SYS_ADJTIMEX = 4124 + SYS_MPROTECT = 4125 + SYS_SIGPROCMASK = 4126 + SYS_CREATE_MODULE = 4127 + SYS_INIT_MODULE = 4128 + SYS_DELETE_MODULE = 4129 + SYS_GET_KERNEL_SYMS = 4130 + SYS_QUOTACTL = 4131 + SYS_GETPGID = 4132 + SYS_FCHDIR = 4133 + SYS_BDFLUSH = 4134 + SYS_SYSFS = 4135 + SYS_PERSONALITY = 4136 + SYS_AFS_SYSCALL = 4137 + SYS_SETFSUID = 4138 + SYS_SETFSGID = 4139 + SYS__LLSEEK = 4140 + SYS_GETDENTS = 4141 + SYS__NEWSELECT = 4142 + SYS_FLOCK = 4143 + SYS_MSYNC = 4144 + SYS_READV = 4145 + SYS_WRITEV = 4146 + SYS_CACHEFLUSH = 4147 + SYS_CACHECTL = 4148 + SYS_SYSMIPS = 4149 + SYS_UNUSED150 = 4150 + SYS_GETSID = 4151 + SYS_FDATASYNC = 4152 + SYS__SYSCTL = 4153 + SYS_MLOCK = 4154 + SYS_MUNLOCK = 4155 + SYS_MLOCKALL = 4156 + SYS_MUNLOCKALL = 4157 + SYS_SCHED_SETPARAM = 4158 + SYS_SCHED_GETPARAM = 4159 + SYS_SCHED_SETSCHEDULER = 4160 + SYS_SCHED_GETSCHEDULER = 4161 + SYS_SCHED_YIELD = 4162 + SYS_SCHED_GET_PRIORITY_MAX = 4163 + SYS_SCHED_GET_PRIORITY_MIN = 4164 + SYS_SCHED_RR_GET_INTERVAL = 4165 + SYS_NANOSLEEP = 4166 + SYS_MREMAP = 4167 + SYS_ACCEPT = 4168 + SYS_BIND = 4169 + SYS_CONNECT = 4170 + SYS_GETPEERNAME = 4171 + SYS_GETSOCKNAME = 4172 + SYS_GETSOCKOPT = 4173 + SYS_LISTEN = 4174 + SYS_RECV = 4175 + SYS_RECVFROM = 4176 + SYS_RECVMSG = 4177 + SYS_SEND = 4178 + SYS_SENDMSG = 4179 + SYS_SENDTO = 4180 + SYS_SETSOCKOPT = 4181 + SYS_SHUTDOWN = 4182 + SYS_SOCKET = 4183 + SYS_SOCKETPAIR = 4184 + SYS_SETRESUID = 4185 + SYS_GETRESUID = 4186 + SYS_QUERY_MODULE = 4187 + SYS_POLL = 4188 + SYS_NFSSERVCTL = 4189 + SYS_SETRESGID = 4190 + SYS_GETRESGID = 4191 + SYS_PRCTL = 4192 + SYS_RT_SIGRETURN = 4193 + SYS_RT_SIGACTION = 4194 + SYS_RT_SIGPROCMASK = 4195 + SYS_RT_SIGPENDING = 4196 + SYS_RT_SIGTIMEDWAIT = 4197 + SYS_RT_SIGQUEUEINFO = 4198 + SYS_RT_SIGSUSPEND = 4199 + SYS_PREAD64 = 4200 + SYS_PWRITE64 = 4201 + SYS_CHOWN = 4202 + SYS_GETCWD = 4203 + SYS_CAPGET = 4204 + SYS_CAPSET = 4205 + SYS_SIGALTSTACK = 4206 + SYS_SENDFILE = 4207 + SYS_GETPMSG = 4208 + SYS_PUTPMSG = 4209 + SYS_MMAP2 = 4210 + SYS_TRUNCATE64 = 4211 + SYS_FTRUNCATE64 = 4212 + SYS_STAT64 = 4213 + SYS_LSTAT64 = 4214 + SYS_FSTAT64 = 4215 + SYS_PIVOT_ROOT = 4216 + SYS_MINCORE = 4217 + SYS_MADVISE = 4218 + SYS_GETDENTS64 = 4219 + SYS_FCNTL64 = 4220 + SYS_RESERVED221 = 4221 + SYS_GETTID = 4222 + SYS_READAHEAD = 4223 + SYS_SETXATTR = 4224 + SYS_LSETXATTR = 4225 + SYS_FSETXATTR = 4226 + SYS_GETXATTR = 4227 + SYS_LGETXATTR = 4228 + SYS_FGETXATTR = 4229 + SYS_LISTXATTR = 4230 + SYS_LLISTXATTR = 4231 + SYS_FLISTXATTR = 4232 + SYS_REMOVEXATTR = 4233 + SYS_LREMOVEXATTR = 4234 + SYS_FREMOVEXATTR = 4235 + SYS_TKILL = 4236 + SYS_SENDFILE64 = 4237 + SYS_FUTEX = 4238 + SYS_SCHED_SETAFFINITY = 4239 + SYS_SCHED_GETAFFINITY = 4240 + SYS_IO_SETUP = 4241 + SYS_IO_DESTROY = 4242 + SYS_IO_GETEVENTS = 4243 + SYS_IO_SUBMIT = 4244 + SYS_IO_CANCEL = 4245 + SYS_EXIT_GROUP = 4246 + SYS_LOOKUP_DCOOKIE = 4247 + SYS_EPOLL_CREATE = 4248 + SYS_EPOLL_CTL = 4249 + SYS_EPOLL_WAIT = 4250 + SYS_REMAP_FILE_PAGES = 4251 + SYS_SET_TID_ADDRESS = 4252 + SYS_RESTART_SYSCALL = 4253 + SYS_FADVISE64 = 4254 + SYS_STATFS64 = 4255 + SYS_FSTATFS64 = 4256 + SYS_TIMER_CREATE = 4257 + SYS_TIMER_SETTIME = 4258 + SYS_TIMER_GETTIME = 4259 + SYS_TIMER_GETOVERRUN = 4260 + SYS_TIMER_DELETE = 4261 + SYS_CLOCK_SETTIME = 4262 + SYS_CLOCK_GETTIME = 4263 + SYS_CLOCK_GETRES = 4264 + SYS_CLOCK_NANOSLEEP = 4265 + SYS_TGKILL = 4266 + SYS_UTIMES = 4267 + SYS_MBIND = 4268 + SYS_GET_MEMPOLICY = 4269 + SYS_SET_MEMPOLICY = 4270 + SYS_MQ_OPEN = 4271 + SYS_MQ_UNLINK = 4272 + SYS_MQ_TIMEDSEND = 4273 + SYS_MQ_TIMEDRECEIVE = 4274 + SYS_MQ_NOTIFY = 4275 + SYS_MQ_GETSETATTR = 4276 + SYS_VSERVER = 4277 + SYS_WAITID = 4278 + SYS_ADD_KEY = 4280 + SYS_REQUEST_KEY = 4281 + SYS_KEYCTL = 4282 + SYS_SET_THREAD_AREA = 4283 + SYS_INOTIFY_INIT = 4284 + SYS_INOTIFY_ADD_WATCH = 4285 + SYS_INOTIFY_RM_WATCH = 4286 + SYS_MIGRATE_PAGES = 4287 + SYS_OPENAT = 4288 + SYS_MKDIRAT = 4289 + SYS_MKNODAT = 4290 + SYS_FCHOWNAT = 4291 + SYS_FUTIMESAT = 4292 + SYS_FSTATAT64 = 4293 + SYS_UNLINKAT = 4294 + SYS_RENAMEAT = 4295 + SYS_LINKAT = 4296 + SYS_SYMLINKAT = 4297 + SYS_READLINKAT = 4298 + SYS_FCHMODAT = 4299 + SYS_FACCESSAT = 4300 + SYS_PSELECT6 = 4301 + SYS_PPOLL = 4302 + SYS_UNSHARE = 4303 + SYS_SPLICE = 4304 + SYS_SYNC_FILE_RANGE = 4305 + SYS_TEE = 4306 + SYS_VMSPLICE = 4307 + SYS_MOVE_PAGES = 4308 + SYS_SET_ROBUST_LIST = 4309 + SYS_GET_ROBUST_LIST = 4310 + SYS_KEXEC_LOAD = 4311 + SYS_GETCPU = 4312 + SYS_EPOLL_PWAIT = 4313 + SYS_IOPRIO_SET = 4314 + SYS_IOPRIO_GET = 4315 + SYS_UTIMENSAT = 4316 + SYS_SIGNALFD = 4317 + SYS_TIMERFD = 4318 + SYS_EVENTFD = 4319 + SYS_FALLOCATE = 4320 + SYS_TIMERFD_CREATE = 4321 + SYS_TIMERFD_GETTIME = 4322 + SYS_TIMERFD_SETTIME = 4323 + SYS_SIGNALFD4 = 4324 + SYS_EVENTFD2 = 4325 + SYS_EPOLL_CREATE1 = 4326 + SYS_DUP3 = 4327 + SYS_PIPE2 = 4328 + SYS_INOTIFY_INIT1 = 4329 + SYS_PREADV = 4330 + SYS_PWRITEV = 4331 + SYS_RT_TGSIGQUEUEINFO = 4332 + SYS_PERF_EVENT_OPEN = 4333 + SYS_ACCEPT4 = 4334 + SYS_RECVMMSG = 4335 + SYS_FANOTIFY_INIT = 4336 + SYS_FANOTIFY_MARK = 4337 + SYS_PRLIMIT64 = 4338 + SYS_NAME_TO_HANDLE_AT = 4339 + SYS_OPEN_BY_HANDLE_AT = 4340 + SYS_CLOCK_ADJTIME = 4341 + SYS_SYNCFS = 4342 + SYS_SENDMMSG = 4343 + SYS_SETNS = 4344 + SYS_PROCESS_VM_READV = 4345 + SYS_PROCESS_VM_WRITEV = 4346 + SYS_LINUX_SYSCALLS = 4346 + SYS_O32_LINUX_SYSCALLS = 4346 + SYS_64_LINUX_SYSCALLS = 4305 + SYS_N32_LINUX_SYSCALLS = 4310 +) diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_386.go b/vendor/golang.org/x/sys/unix/ztypes_linux_386.go index f3ddf53..a363105 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_386.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_386.go @@ -203,6 +203,13 @@ type RawSockaddrHCI struct { Channel uint16 } +type RawSockaddrCAN struct { + Family uint16 + Pad_cgo_0 [2]byte + Ifindex int32 + Addr [8]byte +} + type RawSockaddr struct { Family uint16 Data [14]int8 @@ -326,6 +333,7 @@ const ( SizeofSockaddrLinklayer = 0x14 SizeofSockaddrNetlink = 0xc SizeofSockaddrHCI = 0x6 + SizeofSockaddrCAN = 0x10 SizeofLinger = 0x8 SizeofIPMreq = 0x8 SizeofIPMreqn = 0xc diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_amd64.go b/vendor/golang.org/x/sys/unix/ztypes_linux_amd64.go index a923bef..0573e6c 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_amd64.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_amd64.go @@ -205,6 +205,13 @@ type RawSockaddrHCI struct { Channel uint16 } +type RawSockaddrCAN struct { + Family uint16 + Pad_cgo_0 [2]byte + Ifindex int32 + Addr [8]byte +} + type RawSockaddr struct { Family uint16 Data [14]int8 @@ -330,6 +337,7 @@ const ( SizeofSockaddrLinklayer = 0x14 SizeofSockaddrNetlink = 0xc SizeofSockaddrHCI = 0x6 + SizeofSockaddrCAN = 0x10 SizeofLinger = 0x8 SizeofIPMreq = 0x8 SizeofIPMreqn = 0xc diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_arm.go b/vendor/golang.org/x/sys/unix/ztypes_linux_arm.go index 817ac9c..0578b53 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_arm.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_arm.go @@ -1,6 +1,6 @@ // +build arm,linux // Created by cgo -godefs - DO NOT EDIT -// cgo -godefs types_linux.go +// cgo -godefs types_linux.go | go run mkpost.go package unix @@ -155,6 +155,15 @@ type Flock_t struct { Pad_cgo_1 [4]byte } +const ( + FADV_NORMAL = 0x0 + FADV_RANDOM = 0x1 + FADV_SEQUENTIAL = 0x2 + FADV_WILLNEED = 0x3 + FADV_DONTNEED = 0x4 + FADV_NOREUSE = 0x5 +) + type RawSockaddrInet4 struct { Family uint16 Port uint16 @@ -198,6 +207,13 @@ type RawSockaddrHCI struct { Channel uint16 } +type RawSockaddrCAN struct { + Family uint16 + Pad_cgo_0 [2]byte + Ifindex int32 + Addr [8]byte +} + type RawSockaddr struct { Family uint16 Data [14]uint8 @@ -321,6 +337,7 @@ const ( SizeofSockaddrLinklayer = 0x14 SizeofSockaddrNetlink = 0xc SizeofSockaddrHCI = 0x6 + SizeofSockaddrCAN = 0x10 SizeofLinger = 0x8 SizeofIPMreq = 0x8 SizeofIPMreqn = 0xc diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_arm64.go b/vendor/golang.org/x/sys/unix/ztypes_linux_arm64.go index e786add..808e046 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_arm64.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_arm64.go @@ -206,6 +206,13 @@ type RawSockaddrHCI struct { Channel uint16 } +type RawSockaddrCAN struct { + Family uint16 + Pad_cgo_0 [2]byte + Ifindex int32 + Addr [8]byte +} + type RawSockaddr struct { Family uint16 Data [14]int8 @@ -331,6 +338,7 @@ const ( SizeofSockaddrLinklayer = 0x14 SizeofSockaddrNetlink = 0xc SizeofSockaddrHCI = 0x6 + SizeofSockaddrCAN = 0x10 SizeofLinger = 0x8 SizeofIPMreq = 0x8 SizeofIPMreqn = 0xc diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_mips.go b/vendor/golang.org/x/sys/unix/ztypes_linux_mips.go new file mode 100644 index 0000000..2eaff57 --- /dev/null +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_mips.go @@ -0,0 +1,642 @@ +// +build mips,linux +// Created by cgo -godefs - DO NOT EDIT +// cgo -godefs types_linux.go | go run mkpost.go + +package unix + +const ( + sizeofPtr = 0x4 + sizeofShort = 0x2 + sizeofInt = 0x4 + sizeofLong = 0x4 + sizeofLongLong = 0x8 + PathMax = 0x1000 +) + +type ( + _C_short int16 + _C_int int32 + _C_long int32 + _C_long_long int64 +) + +type Timespec struct { + Sec int32 + Nsec int32 +} + +type Timeval struct { + Sec int32 + Usec int32 +} + +type Timex struct { + Modes uint32 + Offset int32 + Freq int32 + Maxerror int32 + Esterror int32 + Status int32 + Constant int32 + Precision int32 + Tolerance int32 + Time Timeval + Tick int32 + Ppsfreq int32 + Jitter int32 + Shift int32 + Stabil int32 + Jitcnt int32 + Calcnt int32 + Errcnt int32 + Stbcnt int32 + Tai int32 + Pad_cgo_0 [44]byte +} + +type Time_t int32 + +type Tms struct { + Utime int32 + Stime int32 + Cutime int32 + Cstime int32 +} + +type Utimbuf struct { + Actime int32 + Modtime int32 +} + +type Rusage struct { + Utime Timeval + Stime Timeval + Maxrss int32 + Ixrss int32 + Idrss int32 + Isrss int32 + Minflt int32 + Majflt int32 + Nswap int32 + Inblock int32 + Oublock int32 + Msgsnd int32 + Msgrcv int32 + Nsignals int32 + Nvcsw int32 + Nivcsw int32 +} + +type Rlimit struct { + Cur uint64 + Max uint64 +} + +type _Gid_t uint32 + +type Stat_t struct { + Dev uint32 + Pad1 [3]int32 + Ino uint64 + Mode uint32 + Nlink uint32 + Uid uint32 + Gid uint32 + Rdev uint32 + Pad2 [3]int32 + Size int64 + Atim Timespec + Mtim Timespec + Ctim Timespec + Blksize int32 + Pad4 int32 + Blocks int64 + Pad5 [14]int32 +} + +type Statfs_t struct { + Type int32 + Bsize int32 + Frsize int32 + Pad_cgo_0 [4]byte + Blocks uint64 + Bfree uint64 + Files uint64 + Ffree uint64 + Bavail uint64 + Fsid Fsid + Namelen int32 + Flags int32 + Spare [5]int32 + Pad_cgo_1 [4]byte +} + +type Dirent struct { + Ino uint64 + Off int64 + Reclen uint16 + Type uint8 + Name [256]int8 + Pad_cgo_0 [5]byte +} + +type Fsid struct { + X__val [2]int32 +} + +type Flock_t struct { + Type int16 + Whence int16 + Pad_cgo_0 [4]byte + Start int64 + Len int64 + Pid int32 + Pad_cgo_1 [4]byte +} + +const ( + FADV_NORMAL = 0x0 + FADV_RANDOM = 0x1 + FADV_SEQUENTIAL = 0x2 + FADV_WILLNEED = 0x3 + FADV_DONTNEED = 0x4 + FADV_NOREUSE = 0x5 +) + +type RawSockaddrInet4 struct { + Family uint16 + Port uint16 + Addr [4]byte /* in_addr */ + Zero [8]uint8 +} + +type RawSockaddrInet6 struct { + Family uint16 + Port uint16 + Flowinfo uint32 + Addr [16]byte /* in6_addr */ + Scope_id uint32 +} + +type RawSockaddrUnix struct { + Family uint16 + Path [108]int8 +} + +type RawSockaddrLinklayer struct { + Family uint16 + Protocol uint16 + Ifindex int32 + Hatype uint16 + Pkttype uint8 + Halen uint8 + Addr [8]uint8 +} + +type RawSockaddrNetlink struct { + Family uint16 + Pad uint16 + Pid uint32 + Groups uint32 +} + +type RawSockaddrHCI struct { + Family uint16 + Dev uint16 + Channel uint16 +} + +type RawSockaddrCAN struct { + Family uint16 + Pad_cgo_0 [2]byte + Ifindex int32 + Addr [8]byte +} + +type RawSockaddr struct { + Family uint16 + Data [14]int8 +} + +type RawSockaddrAny struct { + Addr RawSockaddr + Pad [96]int8 +} + +type _Socklen uint32 + +type Linger struct { + Onoff int32 + Linger int32 +} + +type Iovec struct { + Base *byte + Len uint32 +} + +type IPMreq struct { + Multiaddr [4]byte /* in_addr */ + Interface [4]byte /* in_addr */ +} + +type IPMreqn struct { + Multiaddr [4]byte /* in_addr */ + Address [4]byte /* in_addr */ + Ifindex int32 +} + +type IPv6Mreq struct { + Multiaddr [16]byte /* in6_addr */ + Interface uint32 +} + +type Msghdr struct { + Name *byte + Namelen uint32 + Iov *Iovec + Iovlen uint32 + Control *byte + Controllen uint32 + Flags int32 +} + +type Cmsghdr struct { + Len uint32 + Level int32 + Type int32 +} + +type Inet4Pktinfo struct { + Ifindex int32 + Spec_dst [4]byte /* in_addr */ + Addr [4]byte /* in_addr */ +} + +type Inet6Pktinfo struct { + Addr [16]byte /* in6_addr */ + Ifindex uint32 +} + +type IPv6MTUInfo struct { + Addr RawSockaddrInet6 + Mtu uint32 +} + +type ICMPv6Filter struct { + Data [8]uint32 +} + +type Ucred struct { + Pid int32 + Uid uint32 + Gid uint32 +} + +type TCPInfo struct { + State uint8 + Ca_state uint8 + Retransmits uint8 + Probes uint8 + Backoff uint8 + Options uint8 + Pad_cgo_0 [2]byte + Rto uint32 + Ato uint32 + Snd_mss uint32 + Rcv_mss uint32 + Unacked uint32 + Sacked uint32 + Lost uint32 + Retrans uint32 + Fackets uint32 + Last_data_sent uint32 + Last_ack_sent uint32 + Last_data_recv uint32 + Last_ack_recv uint32 + Pmtu uint32 + Rcv_ssthresh uint32 + Rtt uint32 + Rttvar uint32 + Snd_ssthresh uint32 + Snd_cwnd uint32 + Advmss uint32 + Reordering uint32 + Rcv_rtt uint32 + Rcv_space uint32 + Total_retrans uint32 +} + +const ( + SizeofSockaddrInet4 = 0x10 + SizeofSockaddrInet6 = 0x1c + SizeofSockaddrAny = 0x70 + SizeofSockaddrUnix = 0x6e + SizeofSockaddrLinklayer = 0x14 + SizeofSockaddrNetlink = 0xc + SizeofSockaddrHCI = 0x6 + SizeofSockaddrCAN = 0x10 + SizeofLinger = 0x8 + SizeofIPMreq = 0x8 + SizeofIPMreqn = 0xc + SizeofIPv6Mreq = 0x14 + SizeofMsghdr = 0x1c + SizeofCmsghdr = 0xc + SizeofInet4Pktinfo = 0xc + SizeofInet6Pktinfo = 0x14 + SizeofIPv6MTUInfo = 0x20 + SizeofICMPv6Filter = 0x20 + SizeofUcred = 0xc + SizeofTCPInfo = 0x68 +) + +const ( + IFA_UNSPEC = 0x0 + IFA_ADDRESS = 0x1 + IFA_LOCAL = 0x2 + IFA_LABEL = 0x3 + IFA_BROADCAST = 0x4 + IFA_ANYCAST = 0x5 + IFA_CACHEINFO = 0x6 + IFA_MULTICAST = 0x7 + IFLA_UNSPEC = 0x0 + IFLA_ADDRESS = 0x1 + IFLA_BROADCAST = 0x2 + IFLA_IFNAME = 0x3 + IFLA_MTU = 0x4 + IFLA_LINK = 0x5 + IFLA_QDISC = 0x6 + IFLA_STATS = 0x7 + IFLA_COST = 0x8 + IFLA_PRIORITY = 0x9 + IFLA_MASTER = 0xa + IFLA_WIRELESS = 0xb + IFLA_PROTINFO = 0xc + IFLA_TXQLEN = 0xd + IFLA_MAP = 0xe + IFLA_WEIGHT = 0xf + IFLA_OPERSTATE = 0x10 + IFLA_LINKMODE = 0x11 + IFLA_LINKINFO = 0x12 + IFLA_NET_NS_PID = 0x13 + IFLA_IFALIAS = 0x14 + IFLA_MAX = 0x1d + RT_SCOPE_UNIVERSE = 0x0 + RT_SCOPE_SITE = 0xc8 + RT_SCOPE_LINK = 0xfd + RT_SCOPE_HOST = 0xfe + RT_SCOPE_NOWHERE = 0xff + RT_TABLE_UNSPEC = 0x0 + RT_TABLE_COMPAT = 0xfc + RT_TABLE_DEFAULT = 0xfd + RT_TABLE_MAIN = 0xfe + RT_TABLE_LOCAL = 0xff + RT_TABLE_MAX = 0xffffffff + RTA_UNSPEC = 0x0 + RTA_DST = 0x1 + RTA_SRC = 0x2 + RTA_IIF = 0x3 + RTA_OIF = 0x4 + RTA_GATEWAY = 0x5 + RTA_PRIORITY = 0x6 + RTA_PREFSRC = 0x7 + RTA_METRICS = 0x8 + RTA_MULTIPATH = 0x9 + RTA_FLOW = 0xb + RTA_CACHEINFO = 0xc + RTA_TABLE = 0xf + RTN_UNSPEC = 0x0 + RTN_UNICAST = 0x1 + RTN_LOCAL = 0x2 + RTN_BROADCAST = 0x3 + RTN_ANYCAST = 0x4 + RTN_MULTICAST = 0x5 + RTN_BLACKHOLE = 0x6 + RTN_UNREACHABLE = 0x7 + RTN_PROHIBIT = 0x8 + RTN_THROW = 0x9 + RTN_NAT = 0xa + RTN_XRESOLVE = 0xb + RTNLGRP_NONE = 0x0 + RTNLGRP_LINK = 0x1 + RTNLGRP_NOTIFY = 0x2 + RTNLGRP_NEIGH = 0x3 + RTNLGRP_TC = 0x4 + RTNLGRP_IPV4_IFADDR = 0x5 + RTNLGRP_IPV4_MROUTE = 0x6 + RTNLGRP_IPV4_ROUTE = 0x7 + RTNLGRP_IPV4_RULE = 0x8 + RTNLGRP_IPV6_IFADDR = 0x9 + RTNLGRP_IPV6_MROUTE = 0xa + RTNLGRP_IPV6_ROUTE = 0xb + RTNLGRP_IPV6_IFINFO = 0xc + RTNLGRP_IPV6_PREFIX = 0x12 + RTNLGRP_IPV6_RULE = 0x13 + RTNLGRP_ND_USEROPT = 0x14 + SizeofNlMsghdr = 0x10 + SizeofNlMsgerr = 0x14 + SizeofRtGenmsg = 0x1 + SizeofNlAttr = 0x4 + SizeofRtAttr = 0x4 + SizeofIfInfomsg = 0x10 + SizeofIfAddrmsg = 0x8 + SizeofRtMsg = 0xc + SizeofRtNexthop = 0x8 +) + +type NlMsghdr struct { + Len uint32 + Type uint16 + Flags uint16 + Seq uint32 + Pid uint32 +} + +type NlMsgerr struct { + Error int32 + Msg NlMsghdr +} + +type RtGenmsg struct { + Family uint8 +} + +type NlAttr struct { + Len uint16 + Type uint16 +} + +type RtAttr struct { + Len uint16 + Type uint16 +} + +type IfInfomsg struct { + Family uint8 + X__ifi_pad uint8 + Type uint16 + Index int32 + Flags uint32 + Change uint32 +} + +type IfAddrmsg struct { + Family uint8 + Prefixlen uint8 + Flags uint8 + Scope uint8 + Index uint32 +} + +type RtMsg struct { + Family uint8 + Dst_len uint8 + Src_len uint8 + Tos uint8 + Table uint8 + Protocol uint8 + Scope uint8 + Type uint8 + Flags uint32 +} + +type RtNexthop struct { + Len uint16 + Flags uint8 + Hops uint8 + Ifindex int32 +} + +const ( + SizeofSockFilter = 0x8 + SizeofSockFprog = 0x8 +) + +type SockFilter struct { + Code uint16 + Jt uint8 + Jf uint8 + K uint32 +} + +type SockFprog struct { + Len uint16 + Pad_cgo_0 [2]byte + Filter *SockFilter +} + +type InotifyEvent struct { + Wd int32 + Mask uint32 + Cookie uint32 + Len uint32 +} + +const SizeofInotifyEvent = 0x10 + +type PtraceRegs struct { + Regs [109]uint32 + U_tsize uint32 + U_dsize uint32 + U_ssize uint32 + Start_code uint32 + Start_data uint32 + Start_stack uint32 + Signal int32 + U_ar0 *byte + Magic uint32 + U_comm [32]int8 +} + +type ptracePsw struct { +} + +type ptraceFpregs struct { +} + +type ptracePer struct { +} + +type FdSet struct { + Bits [32]int32 +} + +type Sysinfo_t struct { + Uptime int32 + Loads [3]uint32 + Totalram uint32 + Freeram uint32 + Sharedram uint32 + Bufferram uint32 + Totalswap uint32 + Freeswap uint32 + Procs uint16 + Pad uint16 + Totalhigh uint32 + Freehigh uint32 + Unit uint32 + X_f [8]int8 +} + +type Utsname struct { + Sysname [65]int8 + Nodename [65]int8 + Release [65]int8 + Version [65]int8 + Machine [65]int8 + Domainname [65]int8 +} + +type Ustat_t struct { + Tfree int32 + Tinode uint32 + Fname [6]int8 + Fpack [6]int8 +} + +type EpollEvent struct { + Events uint32 + PadFd int32 + Fd int32 + Pad int32 +} + +const ( + AT_FDCWD = -0x64 + AT_REMOVEDIR = 0x200 + AT_SYMLINK_FOLLOW = 0x400 + AT_SYMLINK_NOFOLLOW = 0x100 +) + +type PollFd struct { + Fd int32 + Events int16 + Revents int16 +} + +const ( + POLLIN = 0x1 + POLLPRI = 0x2 + POLLOUT = 0x4 + POLLRDHUP = 0x2000 + POLLERR = 0x8 + POLLHUP = 0x10 + POLLNVAL = 0x20 +) + +type Sigset_t struct { + X__val [32]uint32 +} + +const _SC_PAGESIZE = 0x1e + +type Termios struct { + Iflag uint32 + Oflag uint32 + Cflag uint32 + Lflag uint32 + Line uint8 + Cc [23]uint8 + Ispeed uint32 + Ospeed uint32 +} diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_mips64.go b/vendor/golang.org/x/sys/unix/ztypes_linux_mips64.go index b29894d..73e4b76 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_mips64.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_mips64.go @@ -206,6 +206,13 @@ type RawSockaddrHCI struct { Channel uint16 } +type RawSockaddrCAN struct { + Family uint16 + Pad_cgo_0 [2]byte + Ifindex int32 + Addr [8]byte +} + type RawSockaddr struct { Family uint16 Data [14]int8 @@ -330,6 +337,7 @@ const ( SizeofSockaddrLinklayer = 0x14 SizeofSockaddrNetlink = 0xc SizeofSockaddrHCI = 0x6 + SizeofSockaddrCAN = 0x10 SizeofLinger = 0x8 SizeofIPMreq = 0x8 SizeofIPMreqn = 0xc diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_mips64le.go b/vendor/golang.org/x/sys/unix/ztypes_linux_mips64le.go index d9af71b..479ca3e 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_mips64le.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_mips64le.go @@ -206,6 +206,13 @@ type RawSockaddrHCI struct { Channel uint16 } +type RawSockaddrCAN struct { + Family uint16 + Pad_cgo_0 [2]byte + Ifindex int32 + Addr [8]byte +} + type RawSockaddr struct { Family uint16 Data [14]int8 @@ -330,6 +337,7 @@ const ( SizeofSockaddrLinklayer = 0x14 SizeofSockaddrNetlink = 0xc SizeofSockaddrHCI = 0x6 + SizeofSockaddrCAN = 0x10 SizeofLinger = 0x8 SizeofIPMreq = 0x8 SizeofIPMreqn = 0xc diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_mipsle.go b/vendor/golang.org/x/sys/unix/ztypes_linux_mipsle.go new file mode 100644 index 0000000..7617a69 --- /dev/null +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_mipsle.go @@ -0,0 +1,642 @@ +// +build mipsle,linux +// Created by cgo -godefs - DO NOT EDIT +// cgo -godefs types_linux.go | go run mkpost.go + +package unix + +const ( + sizeofPtr = 0x4 + sizeofShort = 0x2 + sizeofInt = 0x4 + sizeofLong = 0x4 + sizeofLongLong = 0x8 + PathMax = 0x1000 +) + +type ( + _C_short int16 + _C_int int32 + _C_long int32 + _C_long_long int64 +) + +type Timespec struct { + Sec int32 + Nsec int32 +} + +type Timeval struct { + Sec int32 + Usec int32 +} + +type Timex struct { + Modes uint32 + Offset int32 + Freq int32 + Maxerror int32 + Esterror int32 + Status int32 + Constant int32 + Precision int32 + Tolerance int32 + Time Timeval + Tick int32 + Ppsfreq int32 + Jitter int32 + Shift int32 + Stabil int32 + Jitcnt int32 + Calcnt int32 + Errcnt int32 + Stbcnt int32 + Tai int32 + Pad_cgo_0 [44]byte +} + +type Time_t int32 + +type Tms struct { + Utime int32 + Stime int32 + Cutime int32 + Cstime int32 +} + +type Utimbuf struct { + Actime int32 + Modtime int32 +} + +type Rusage struct { + Utime Timeval + Stime Timeval + Maxrss int32 + Ixrss int32 + Idrss int32 + Isrss int32 + Minflt int32 + Majflt int32 + Nswap int32 + Inblock int32 + Oublock int32 + Msgsnd int32 + Msgrcv int32 + Nsignals int32 + Nvcsw int32 + Nivcsw int32 +} + +type Rlimit struct { + Cur uint64 + Max uint64 +} + +type _Gid_t uint32 + +type Stat_t struct { + Dev uint32 + Pad1 [3]int32 + Ino uint64 + Mode uint32 + Nlink uint32 + Uid uint32 + Gid uint32 + Rdev uint32 + Pad2 [3]int32 + Size int64 + Atim Timespec + Mtim Timespec + Ctim Timespec + Blksize int32 + Pad4 int32 + Blocks int64 + Pad5 [14]int32 +} + +type Statfs_t struct { + Type int32 + Bsize int32 + Frsize int32 + Pad_cgo_0 [4]byte + Blocks uint64 + Bfree uint64 + Files uint64 + Ffree uint64 + Bavail uint64 + Fsid Fsid + Namelen int32 + Flags int32 + Spare [5]int32 + Pad_cgo_1 [4]byte +} + +type Dirent struct { + Ino uint64 + Off int64 + Reclen uint16 + Type uint8 + Name [256]int8 + Pad_cgo_0 [5]byte +} + +type Fsid struct { + X__val [2]int32 +} + +type Flock_t struct { + Type int16 + Whence int16 + Pad_cgo_0 [4]byte + Start int64 + Len int64 + Pid int32 + Pad_cgo_1 [4]byte +} + +const ( + FADV_NORMAL = 0x0 + FADV_RANDOM = 0x1 + FADV_SEQUENTIAL = 0x2 + FADV_WILLNEED = 0x3 + FADV_DONTNEED = 0x4 + FADV_NOREUSE = 0x5 +) + +type RawSockaddrInet4 struct { + Family uint16 + Port uint16 + Addr [4]byte /* in_addr */ + Zero [8]uint8 +} + +type RawSockaddrInet6 struct { + Family uint16 + Port uint16 + Flowinfo uint32 + Addr [16]byte /* in6_addr */ + Scope_id uint32 +} + +type RawSockaddrUnix struct { + Family uint16 + Path [108]int8 +} + +type RawSockaddrLinklayer struct { + Family uint16 + Protocol uint16 + Ifindex int32 + Hatype uint16 + Pkttype uint8 + Halen uint8 + Addr [8]uint8 +} + +type RawSockaddrNetlink struct { + Family uint16 + Pad uint16 + Pid uint32 + Groups uint32 +} + +type RawSockaddrHCI struct { + Family uint16 + Dev uint16 + Channel uint16 +} + +type RawSockaddrCAN struct { + Family uint16 + Pad_cgo_0 [2]byte + Ifindex int32 + Addr [8]byte +} + +type RawSockaddr struct { + Family uint16 + Data [14]int8 +} + +type RawSockaddrAny struct { + Addr RawSockaddr + Pad [96]int8 +} + +type _Socklen uint32 + +type Linger struct { + Onoff int32 + Linger int32 +} + +type Iovec struct { + Base *byte + Len uint32 +} + +type IPMreq struct { + Multiaddr [4]byte /* in_addr */ + Interface [4]byte /* in_addr */ +} + +type IPMreqn struct { + Multiaddr [4]byte /* in_addr */ + Address [4]byte /* in_addr */ + Ifindex int32 +} + +type IPv6Mreq struct { + Multiaddr [16]byte /* in6_addr */ + Interface uint32 +} + +type Msghdr struct { + Name *byte + Namelen uint32 + Iov *Iovec + Iovlen uint32 + Control *byte + Controllen uint32 + Flags int32 +} + +type Cmsghdr struct { + Len uint32 + Level int32 + Type int32 +} + +type Inet4Pktinfo struct { + Ifindex int32 + Spec_dst [4]byte /* in_addr */ + Addr [4]byte /* in_addr */ +} + +type Inet6Pktinfo struct { + Addr [16]byte /* in6_addr */ + Ifindex uint32 +} + +type IPv6MTUInfo struct { + Addr RawSockaddrInet6 + Mtu uint32 +} + +type ICMPv6Filter struct { + Data [8]uint32 +} + +type Ucred struct { + Pid int32 + Uid uint32 + Gid uint32 +} + +type TCPInfo struct { + State uint8 + Ca_state uint8 + Retransmits uint8 + Probes uint8 + Backoff uint8 + Options uint8 + Pad_cgo_0 [2]byte + Rto uint32 + Ato uint32 + Snd_mss uint32 + Rcv_mss uint32 + Unacked uint32 + Sacked uint32 + Lost uint32 + Retrans uint32 + Fackets uint32 + Last_data_sent uint32 + Last_ack_sent uint32 + Last_data_recv uint32 + Last_ack_recv uint32 + Pmtu uint32 + Rcv_ssthresh uint32 + Rtt uint32 + Rttvar uint32 + Snd_ssthresh uint32 + Snd_cwnd uint32 + Advmss uint32 + Reordering uint32 + Rcv_rtt uint32 + Rcv_space uint32 + Total_retrans uint32 +} + +const ( + SizeofSockaddrInet4 = 0x10 + SizeofSockaddrInet6 = 0x1c + SizeofSockaddrAny = 0x70 + SizeofSockaddrUnix = 0x6e + SizeofSockaddrLinklayer = 0x14 + SizeofSockaddrNetlink = 0xc + SizeofSockaddrHCI = 0x6 + SizeofSockaddrCAN = 0x10 + SizeofLinger = 0x8 + SizeofIPMreq = 0x8 + SizeofIPMreqn = 0xc + SizeofIPv6Mreq = 0x14 + SizeofMsghdr = 0x1c + SizeofCmsghdr = 0xc + SizeofInet4Pktinfo = 0xc + SizeofInet6Pktinfo = 0x14 + SizeofIPv6MTUInfo = 0x20 + SizeofICMPv6Filter = 0x20 + SizeofUcred = 0xc + SizeofTCPInfo = 0x68 +) + +const ( + IFA_UNSPEC = 0x0 + IFA_ADDRESS = 0x1 + IFA_LOCAL = 0x2 + IFA_LABEL = 0x3 + IFA_BROADCAST = 0x4 + IFA_ANYCAST = 0x5 + IFA_CACHEINFO = 0x6 + IFA_MULTICAST = 0x7 + IFLA_UNSPEC = 0x0 + IFLA_ADDRESS = 0x1 + IFLA_BROADCAST = 0x2 + IFLA_IFNAME = 0x3 + IFLA_MTU = 0x4 + IFLA_LINK = 0x5 + IFLA_QDISC = 0x6 + IFLA_STATS = 0x7 + IFLA_COST = 0x8 + IFLA_PRIORITY = 0x9 + IFLA_MASTER = 0xa + IFLA_WIRELESS = 0xb + IFLA_PROTINFO = 0xc + IFLA_TXQLEN = 0xd + IFLA_MAP = 0xe + IFLA_WEIGHT = 0xf + IFLA_OPERSTATE = 0x10 + IFLA_LINKMODE = 0x11 + IFLA_LINKINFO = 0x12 + IFLA_NET_NS_PID = 0x13 + IFLA_IFALIAS = 0x14 + IFLA_MAX = 0x2a + RT_SCOPE_UNIVERSE = 0x0 + RT_SCOPE_SITE = 0xc8 + RT_SCOPE_LINK = 0xfd + RT_SCOPE_HOST = 0xfe + RT_SCOPE_NOWHERE = 0xff + RT_TABLE_UNSPEC = 0x0 + RT_TABLE_COMPAT = 0xfc + RT_TABLE_DEFAULT = 0xfd + RT_TABLE_MAIN = 0xfe + RT_TABLE_LOCAL = 0xff + RT_TABLE_MAX = 0xffffffff + RTA_UNSPEC = 0x0 + RTA_DST = 0x1 + RTA_SRC = 0x2 + RTA_IIF = 0x3 + RTA_OIF = 0x4 + RTA_GATEWAY = 0x5 + RTA_PRIORITY = 0x6 + RTA_PREFSRC = 0x7 + RTA_METRICS = 0x8 + RTA_MULTIPATH = 0x9 + RTA_FLOW = 0xb + RTA_CACHEINFO = 0xc + RTA_TABLE = 0xf + RTN_UNSPEC = 0x0 + RTN_UNICAST = 0x1 + RTN_LOCAL = 0x2 + RTN_BROADCAST = 0x3 + RTN_ANYCAST = 0x4 + RTN_MULTICAST = 0x5 + RTN_BLACKHOLE = 0x6 + RTN_UNREACHABLE = 0x7 + RTN_PROHIBIT = 0x8 + RTN_THROW = 0x9 + RTN_NAT = 0xa + RTN_XRESOLVE = 0xb + RTNLGRP_NONE = 0x0 + RTNLGRP_LINK = 0x1 + RTNLGRP_NOTIFY = 0x2 + RTNLGRP_NEIGH = 0x3 + RTNLGRP_TC = 0x4 + RTNLGRP_IPV4_IFADDR = 0x5 + RTNLGRP_IPV4_MROUTE = 0x6 + RTNLGRP_IPV4_ROUTE = 0x7 + RTNLGRP_IPV4_RULE = 0x8 + RTNLGRP_IPV6_IFADDR = 0x9 + RTNLGRP_IPV6_MROUTE = 0xa + RTNLGRP_IPV6_ROUTE = 0xb + RTNLGRP_IPV6_IFINFO = 0xc + RTNLGRP_IPV6_PREFIX = 0x12 + RTNLGRP_IPV6_RULE = 0x13 + RTNLGRP_ND_USEROPT = 0x14 + SizeofNlMsghdr = 0x10 + SizeofNlMsgerr = 0x14 + SizeofRtGenmsg = 0x1 + SizeofNlAttr = 0x4 + SizeofRtAttr = 0x4 + SizeofIfInfomsg = 0x10 + SizeofIfAddrmsg = 0x8 + SizeofRtMsg = 0xc + SizeofRtNexthop = 0x8 +) + +type NlMsghdr struct { + Len uint32 + Type uint16 + Flags uint16 + Seq uint32 + Pid uint32 +} + +type NlMsgerr struct { + Error int32 + Msg NlMsghdr +} + +type RtGenmsg struct { + Family uint8 +} + +type NlAttr struct { + Len uint16 + Type uint16 +} + +type RtAttr struct { + Len uint16 + Type uint16 +} + +type IfInfomsg struct { + Family uint8 + X__ifi_pad uint8 + Type uint16 + Index int32 + Flags uint32 + Change uint32 +} + +type IfAddrmsg struct { + Family uint8 + Prefixlen uint8 + Flags uint8 + Scope uint8 + Index uint32 +} + +type RtMsg struct { + Family uint8 + Dst_len uint8 + Src_len uint8 + Tos uint8 + Table uint8 + Protocol uint8 + Scope uint8 + Type uint8 + Flags uint32 +} + +type RtNexthop struct { + Len uint16 + Flags uint8 + Hops uint8 + Ifindex int32 +} + +const ( + SizeofSockFilter = 0x8 + SizeofSockFprog = 0x8 +) + +type SockFilter struct { + Code uint16 + Jt uint8 + Jf uint8 + K uint32 +} + +type SockFprog struct { + Len uint16 + Pad_cgo_0 [2]byte + Filter *SockFilter +} + +type InotifyEvent struct { + Wd int32 + Mask uint32 + Cookie uint32 + Len uint32 +} + +const SizeofInotifyEvent = 0x10 + +type PtraceRegs struct { + Regs [109]uint32 + U_tsize uint32 + U_dsize uint32 + U_ssize uint32 + Start_code uint32 + Start_data uint32 + Start_stack uint32 + Signal int32 + U_ar0 *byte + Magic uint32 + U_comm [32]int8 +} + +type ptracePsw struct { +} + +type ptraceFpregs struct { +} + +type ptracePer struct { +} + +type FdSet struct { + Bits [32]int32 +} + +type Sysinfo_t struct { + Uptime int32 + Loads [3]uint32 + Totalram uint32 + Freeram uint32 + Sharedram uint32 + Bufferram uint32 + Totalswap uint32 + Freeswap uint32 + Procs uint16 + Pad uint16 + Totalhigh uint32 + Freehigh uint32 + Unit uint32 + X_f [8]int8 +} + +type Utsname struct { + Sysname [65]int8 + Nodename [65]int8 + Release [65]int8 + Version [65]int8 + Machine [65]int8 + Domainname [65]int8 +} + +type Ustat_t struct { + Tfree int32 + Tinode uint32 + Fname [6]int8 + Fpack [6]int8 +} + +type EpollEvent struct { + Events uint32 + PadFd int32 + Fd int32 + Pad int32 +} + +const ( + AT_FDCWD = -0x64 + AT_REMOVEDIR = 0x200 + AT_SYMLINK_FOLLOW = 0x400 + AT_SYMLINK_NOFOLLOW = 0x100 +) + +type PollFd struct { + Fd int32 + Events int16 + Revents int16 +} + +const ( + POLLIN = 0x1 + POLLPRI = 0x2 + POLLOUT = 0x4 + POLLRDHUP = 0x2000 + POLLERR = 0x8 + POLLHUP = 0x10 + POLLNVAL = 0x20 +) + +type Sigset_t struct { + X__val [32]uint32 +} + +const _SC_PAGESIZE = 0x1e + +type Termios struct { + Iflag uint32 + Oflag uint32 + Cflag uint32 + Lflag uint32 + Line uint8 + Cc [23]uint8 + Ispeed uint32 + Ospeed uint32 +} diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_ppc64.go b/vendor/golang.org/x/sys/unix/ztypes_linux_ppc64.go index 4218170..2db548b 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_ppc64.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_ppc64.go @@ -207,6 +207,13 @@ type RawSockaddrHCI struct { Channel uint16 } +type RawSockaddrCAN struct { + Family uint16 + Pad_cgo_0 [2]byte + Ifindex int32 + Addr [8]byte +} + type RawSockaddr struct { Family uint16 Data [14]uint8 @@ -332,6 +339,7 @@ const ( SizeofSockaddrLinklayer = 0x14 SizeofSockaddrNetlink = 0xc SizeofSockaddrHCI = 0x6 + SizeofSockaddrCAN = 0x10 SizeofLinger = 0x8 SizeofIPMreq = 0x8 SizeofIPMreqn = 0xc diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_ppc64le.go b/vendor/golang.org/x/sys/unix/ztypes_linux_ppc64le.go index 7db4c78..4bfdcc0 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_ppc64le.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_ppc64le.go @@ -207,6 +207,13 @@ type RawSockaddrHCI struct { Channel uint16 } +type RawSockaddrCAN struct { + Family uint16 + Pad_cgo_0 [2]byte + Ifindex int32 + Addr [8]byte +} + type RawSockaddr struct { Family uint16 Data [14]uint8 @@ -332,6 +339,7 @@ const ( SizeofSockaddrLinklayer = 0x14 SizeofSockaddrNetlink = 0xc SizeofSockaddrHCI = 0x6 + SizeofSockaddrCAN = 0x10 SizeofLinger = 0x8 SizeofIPMreq = 0x8 SizeofIPMreqn = 0xc diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_s390x.go b/vendor/golang.org/x/sys/unix/ztypes_linux_s390x.go index 76ee57c..435cd79 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_s390x.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_s390x.go @@ -206,6 +206,13 @@ type RawSockaddrHCI struct { Channel uint16 } +type RawSockaddrCAN struct { + Family uint16 + Pad_cgo_0 [2]byte + Ifindex int32 + Addr [8]byte +} + type RawSockaddr struct { Family uint16 Data [14]int8 @@ -330,6 +337,7 @@ const ( SizeofSockaddrLinklayer = 0x14 SizeofSockaddrNetlink = 0xc SizeofSockaddrHCI = 0x6 + SizeofSockaddrCAN = 0x10 SizeofLinger = 0x8 SizeofIPMreq = 0x8 SizeofIPMreqn = 0xc diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_sparc64.go b/vendor/golang.org/x/sys/unix/ztypes_linux_sparc64.go index 7d18b70..439f969 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_sparc64.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_sparc64.go @@ -211,6 +211,13 @@ type RawSockaddrHCI struct { Channel uint16 } +type RawSockaddrCAN struct { + Family uint16 + Pad_cgo_0 [2]byte + Ifindex int32 + Addr [8]byte +} + type RawSockaddr struct { Family uint16 Data [14]int8 @@ -335,6 +342,7 @@ const ( SizeofSockaddrLinklayer = 0x14 SizeofSockaddrNetlink = 0xc SizeofSockaddrHCI = 0x6 + SizeofSockaddrCAN = 0x10 SizeofLinger = 0x8 SizeofIPMreq = 0x8 SizeofIPMreqn = 0xc diff --git a/vendor/golang.org/x/text/unicode/norm/readwriter.go b/vendor/golang.org/x/text/unicode/norm/readwriter.go index 4fa0e04..d926ee9 100644 --- a/vendor/golang.org/x/text/unicode/norm/readwriter.go +++ b/vendor/golang.org/x/text/unicode/norm/readwriter.go @@ -112,7 +112,6 @@ func (r *normReader) Read(p []byte) (int, error) { } } } - panic("should not reach here") } // Reader returns a new reader that implements Read diff --git a/vendor/gopkg.in/bsm/ratelimit.v1/Makefile b/vendor/gopkg.in/bsm/ratelimit.v1/Makefile deleted file mode 100644 index aa713cc..0000000 --- a/vendor/gopkg.in/bsm/ratelimit.v1/Makefile +++ /dev/null @@ -1,16 +0,0 @@ -default: test - -testdeps: - @go get github.com/onsi/ginkgo - @go get github.com/onsi/gomega - -test: testdeps - @go test ./... - -testrace: testdeps - @go test ./... -race - -testall: test testrace - -bench: - @go test ./... -run=NONE -bench=. diff --git a/vendor/gopkg.in/bsm/ratelimit.v1/README.md b/vendor/gopkg.in/bsm/ratelimit.v1/README.md deleted file mode 100644 index bf48e94..0000000 --- a/vendor/gopkg.in/bsm/ratelimit.v1/README.md +++ /dev/null @@ -1,54 +0,0 @@ -# RateLimit [![Build Status](https://travis-ci.org/bsm/ratelimit.png?branch=master)](https://travis-ci.org/bsm/ratelimit) - -Simple, thread-safe Go rate-limiter. -Inspired by Antti Huima's algorithm on http://stackoverflow.com/a/668327 - -### Example - -```go -package main - -import ( - "github.com/bsm/ratelimit" - "log" -) - -func main() { - // Create a new rate-limiter, allowing up-to 10 calls - // per second - rl := ratelimit.New(10, time.Second) - - for i:=0; i<20; i++ { - if rl.Limit() { - fmt.Println("DOH! Over limit!") - } else { - fmt.Println("OK") - } - } -} -``` - -### Licence - -``` -Copyright (c) 2015 Black Square Media - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -``` diff --git a/vendor/gopkg.in/bsm/ratelimit.v1/ratelimit.go b/vendor/gopkg.in/bsm/ratelimit.v1/ratelimit.go deleted file mode 100644 index d006009..0000000 --- a/vendor/gopkg.in/bsm/ratelimit.v1/ratelimit.go +++ /dev/null @@ -1,96 +0,0 @@ -/* -Simple, thread-safe Go rate-limiter. -Inspired by Antti Huima's algorithm on http://stackoverflow.com/a/668327 - -Example: - - // Create a new rate-limiter, allowing up-to 10 calls - // per second - rl := ratelimit.New(10, time.Second) - - for i:=0; i<20; i++ { - if rl.Limit() { - fmt.Println("DOH! Over limit!") - } else { - fmt.Println("OK") - } - } -*/ -package ratelimit - -import ( - "sync/atomic" - "time" -) - -// RateLimiter instances are thread-safe. -type RateLimiter struct { - rate, allowance, max, unit, lastCheck uint64 -} - -// New creates a new rate limiter instance -func New(rate int, per time.Duration) *RateLimiter { - nano := uint64(per) - if nano < 1 { - nano = uint64(time.Second) - } - if rate < 1 { - rate = 1 - } - - return &RateLimiter{ - rate: uint64(rate), // store the rate - allowance: uint64(rate) * nano, // set our allowance to max in the beginning - max: uint64(rate) * nano, // remember our maximum allowance - unit: nano, // remember our unit size - - lastCheck: unixNano(), - } -} - -// UpdateRate allows to update the allowed rate -func (rl *RateLimiter) UpdateRate(rate int) { - atomic.StoreUint64(&rl.rate, uint64(rate)) - atomic.StoreUint64(&rl.max, uint64(rate)*rl.unit) -} - -// Limit returns true if rate was exceeded -func (rl *RateLimiter) Limit() bool { - // Calculate the number of ns that have passed since our last call - now := unixNano() - passed := now - atomic.SwapUint64(&rl.lastCheck, now) - - // Add them to our allowance - rate := atomic.LoadUint64(&rl.rate) - current := atomic.AddUint64(&rl.allowance, passed*rate) - - // Ensure our allowance is not over maximum - if max := atomic.LoadUint64(&rl.max); current > max { - atomic.AddUint64(&rl.allowance, max-current) - current = max - } - - // If our allowance is less than one unit, rate-limit! - if current < rl.unit { - return true - } - - // Not limited, subtract a unit - atomic.AddUint64(&rl.allowance, -rl.unit) - return false -} - -// Undo reverts the last Limit() call, returning consumed allowance -func (rl *RateLimiter) Undo() { - current := atomic.AddUint64(&rl.allowance, rl.unit) - - // Ensure our allowance is not over maximum - if max := atomic.LoadUint64(&rl.max); current > max { - atomic.AddUint64(&rl.allowance, max-current) - } -} - -// now as unix nanoseconds -func unixNano() uint64 { - return uint64(time.Now().UnixNano()) -} diff --git a/vendor/github.com/pkg/sftp/LICENSE b/vendor/gopkg.in/cheggaaa/pb.v1/LICENSE similarity index 58% rename from vendor/github.com/pkg/sftp/LICENSE rename to vendor/gopkg.in/cheggaaa/pb.v1/LICENSE index b7b5392..5119703 100644 --- a/vendor/github.com/pkg/sftp/LICENSE +++ b/vendor/gopkg.in/cheggaaa/pb.v1/LICENSE @@ -1,9 +1,12 @@ -Copyright (c) 2013, Dave Cheney +Copyright (c) 2012-2015, Sergey Cherepanov All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. +* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +* Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \ No newline at end of file diff --git a/vendor/gopkg.in/cheggaaa/pb.v1/README.md b/vendor/gopkg.in/cheggaaa/pb.v1/README.md new file mode 100644 index 0000000..31babb3 --- /dev/null +++ b/vendor/gopkg.in/cheggaaa/pb.v1/README.md @@ -0,0 +1,176 @@ +# Terminal progress bar for Go + +Simple progress bar for console programs. + + +## Installation + +``` +go get gopkg.in/cheggaaa/pb.v1 +``` + +## Usage + +```Go +package main + +import ( + "gopkg.in/cheggaaa/pb.v1" + "time" +) + +func main() { + count := 100000 + bar := pb.StartNew(count) + for i := 0; i < count; i++ { + bar.Increment() + time.Sleep(time.Millisecond) + } + bar.FinishPrint("The End!") +} + +``` + +Result will be like this: + +``` +> go run test.go +37158 / 100000 [================>_______________________________] 37.16% 1m11s +``` + +## Customization + +```Go +// create bar +bar := pb.New(count) + +// refresh info every second (default 200ms) +bar.SetRefreshRate(time.Second) + +// show percents (by default already true) +bar.ShowPercent = true + +// show bar (by default already true) +bar.ShowBar = true + +// no counters +bar.ShowCounters = false + +// show "time left" +bar.ShowTimeLeft = true + +// show average speed +bar.ShowSpeed = true + +// sets the width of the progress bar +bar.SetWidth(80) + +// sets the width of the progress bar, but if terminal size smaller will be ignored +bar.SetMaxWidth(80) + +// convert output to readable format (like KB, MB) +bar.SetUnits(pb.U_BYTES) + +// and start +bar.Start() +``` + +## Progress bar for IO Operations + +```go +// create and start bar +bar := pb.New(myDataLen).SetUnits(pb.U_BYTES) +bar.Start() + +// my io.Reader +r := myReader + +// my io.Writer +w := myWriter + +// create proxy reader +reader := bar.NewProxyReader(r) + +// and copy from pb reader +io.Copy(w, reader) + +``` + +```go +// create and start bar +bar := pb.New(myDataLen).SetUnits(pb.U_BYTES) +bar.Start() + +// my io.Reader +r := myReader + +// my io.Writer +w := myWriter + +// create multi writer +writer := io.MultiWriter(w, bar) + +// and copy +io.Copy(writer, r) + +bar.Finish() +``` + +## Custom Progress Bar Look-and-feel + +```go +bar.Format("<.- >") +``` + +## Multiple Progress Bars (experimental and unstable) + +Do not print to terminal while pool is active. + +```go +package main + +import ( + "math/rand" + "sync" + "time" + + "gopkg.in/cheggaaa/pb.v1" +) + +func main() { + // create bars + first := pb.New(200).Prefix("First ") + second := pb.New(200).Prefix("Second ") + third := pb.New(200).Prefix("Third ") + // start pool + pool, err := pb.StartPool(first, second, third) + if err != nil { + panic(err) + } + // update bars + wg := new(sync.WaitGroup) + for _, bar := range []*pb.ProgressBar{first, second, third} { + wg.Add(1) + go func(cb *pb.ProgressBar) { + for n := 0; n < 200; n++ { + cb.Increment() + time.Sleep(time.Millisecond * time.Duration(rand.Intn(100))) + } + cb.Finish() + wg.Done() + }(bar) + } + wg.Wait() + // close pool + pool.Stop() +} +``` + +The result will be as follows: + +``` +$ go run example/multiple.go +First 141 / 1000 [===============>---------------------------------------] 14.10 % 44s +Second 139 / 1000 [==============>---------------------------------------] 13.90 % 44s +Third 152 / 1000 [================>--------------------------------------] 15.20 % 40s +``` diff --git a/vendor/gopkg.in/cheggaaa/pb.v1/format.go b/vendor/gopkg.in/cheggaaa/pb.v1/format.go new file mode 100644 index 0000000..d5aeff7 --- /dev/null +++ b/vendor/gopkg.in/cheggaaa/pb.v1/format.go @@ -0,0 +1,87 @@ +package pb + +import ( + "fmt" + "strings" + "time" +) + +type Units int + +const ( + // U_NO are default units, they represent a simple value and are not formatted at all. + U_NO Units = iota + // U_BYTES units are formatted in a human readable way (b, Bb, Mb, ...) + U_BYTES + // U_DURATION units are formatted in a human readable way (3h14m15s) + U_DURATION +) + +func Format(i int64) *formatter { + return &formatter{n: i} +} + +type formatter struct { + n int64 + unit Units + width int + perSec bool +} + +func (f *formatter) Value(n int64) *formatter { + f.n = n + return f +} + +func (f *formatter) To(unit Units) *formatter { + f.unit = unit + return f +} + +func (f *formatter) Width(width int) *formatter { + f.width = width + return f +} + +func (f *formatter) PerSec() *formatter { + f.perSec = true + return f +} + +func (f *formatter) String() (out string) { + switch f.unit { + case U_BYTES: + out = formatBytes(f.n) + case U_DURATION: + d := time.Duration(f.n) + if d > time.Hour*24 { + out = fmt.Sprintf("%dd", d/24/time.Hour) + d -= (d / time.Hour / 24) * (time.Hour * 24) + } + out = fmt.Sprintf("%s%v", out, d) + default: + out = fmt.Sprintf(fmt.Sprintf("%%%dd", f.width), f.n) + } + if f.perSec { + out += "/s" + } + return +} + +// Convert bytes to human readable string. Like a 2 MB, 64.2 KB, 52 B +func formatBytes(i int64) (result string) { + switch { + case i > (1024 * 1024 * 1024 * 1024): + result = fmt.Sprintf("%.02f TB", float64(i)/1024/1024/1024/1024) + case i > (1024 * 1024 * 1024): + result = fmt.Sprintf("%.02f GB", float64(i)/1024/1024/1024) + case i > (1024 * 1024): + result = fmt.Sprintf("%.02f MB", float64(i)/1024/1024) + case i > 1024: + result = fmt.Sprintf("%.02f KB", float64(i)/1024) + default: + result = fmt.Sprintf("%d B", i) + } + result = strings.Trim(result, " ") + return +} diff --git a/vendor/gopkg.in/cheggaaa/pb.v1/pb.go b/vendor/gopkg.in/cheggaaa/pb.v1/pb.go new file mode 100644 index 0000000..f1f15bf --- /dev/null +++ b/vendor/gopkg.in/cheggaaa/pb.v1/pb.go @@ -0,0 +1,444 @@ +// Simple console progress bars +package pb + +import ( + "fmt" + "io" + "math" + "strings" + "sync" + "sync/atomic" + "time" + "unicode/utf8" +) + +// Current version +const Version = "1.0.6" + +const ( + // Default refresh rate - 200ms + DEFAULT_REFRESH_RATE = time.Millisecond * 200 + FORMAT = "[=>-]" +) + +// DEPRECATED +// variables for backward compatibility, from now do not work +// use pb.Format and pb.SetRefreshRate +var ( + DefaultRefreshRate = DEFAULT_REFRESH_RATE + BarStart, BarEnd, Empty, Current, CurrentN string +) + +// Create new progress bar object +func New(total int) *ProgressBar { + return New64(int64(total)) +} + +// Create new progress bar object using int64 as total +func New64(total int64) *ProgressBar { + pb := &ProgressBar{ + Total: total, + RefreshRate: DEFAULT_REFRESH_RATE, + ShowPercent: true, + ShowCounters: true, + ShowBar: true, + ShowTimeLeft: true, + ShowFinalTime: true, + Units: U_NO, + ManualUpdate: false, + finish: make(chan struct{}), + currentValue: -1, + mu: new(sync.Mutex), + } + return pb.Format(FORMAT) +} + +// Create new object and start +func StartNew(total int) *ProgressBar { + return New(total).Start() +} + +// Callback for custom output +// For example: +// bar.Callback = func(s string) { +// mySuperPrint(s) +// } +// +type Callback func(out string) + +type ProgressBar struct { + current int64 // current must be first member of struct (https://code.google.com/p/go/issues/detail?id=5278) + + Total int64 + RefreshRate time.Duration + ShowPercent, ShowCounters bool + ShowSpeed, ShowTimeLeft, ShowBar bool + ShowFinalTime bool + Output io.Writer + Callback Callback + NotPrint bool + Units Units + Width int + ForceWidth bool + ManualUpdate bool + AutoStat bool + + // Default width for the time box. + UnitsWidth int + TimeBoxWidth int + + finishOnce sync.Once //Guards isFinish + finish chan struct{} + isFinish bool + + startTime time.Time + startValue int64 + currentValue int64 + + prefix, postfix string + + mu *sync.Mutex + lastPrint string + + BarStart string + BarEnd string + Empty string + Current string + CurrentN string + + AlwaysUpdate bool +} + +// Start print +func (pb *ProgressBar) Start() *ProgressBar { + pb.startTime = time.Now() + pb.startValue = pb.current + if pb.Total == 0 { + pb.ShowTimeLeft = false + pb.ShowPercent = false + pb.AutoStat = false + } + if !pb.ManualUpdate { + pb.Update() // Initial printing of the bar before running the bar refresher. + go pb.refresher() + } + return pb +} + +// Increment current value +func (pb *ProgressBar) Increment() int { + return pb.Add(1) +} + +// Get current value +func (pb *ProgressBar) Get() int64 { + c := atomic.LoadInt64(&pb.current) + return c +} + +// Set current value +func (pb *ProgressBar) Set(current int) *ProgressBar { + return pb.Set64(int64(current)) +} + +// Set64 sets the current value as int64 +func (pb *ProgressBar) Set64(current int64) *ProgressBar { + atomic.StoreInt64(&pb.current, current) + return pb +} + +// Add to current value +func (pb *ProgressBar) Add(add int) int { + return int(pb.Add64(int64(add))) +} + +func (pb *ProgressBar) Add64(add int64) int64 { + return atomic.AddInt64(&pb.current, add) +} + +// Set prefix string +func (pb *ProgressBar) Prefix(prefix string) *ProgressBar { + pb.prefix = prefix + return pb +} + +// Set postfix string +func (pb *ProgressBar) Postfix(postfix string) *ProgressBar { + pb.postfix = postfix + return pb +} + +// Set custom format for bar +// Example: bar.Format("[=>_]") +// Example: bar.Format("[\x00=\x00>\x00-\x00]") // \x00 is the delimiter +func (pb *ProgressBar) Format(format string) *ProgressBar { + var formatEntries []string + if len(format) == 5 { + formatEntries = strings.Split(format, "") + } else { + formatEntries = strings.Split(format, "\x00") + } + if len(formatEntries) == 5 { + pb.BarStart = formatEntries[0] + pb.BarEnd = formatEntries[4] + pb.Empty = formatEntries[3] + pb.Current = formatEntries[1] + pb.CurrentN = formatEntries[2] + } + return pb +} + +// Set bar refresh rate +func (pb *ProgressBar) SetRefreshRate(rate time.Duration) *ProgressBar { + pb.RefreshRate = rate + return pb +} + +// Set units +// bar.SetUnits(U_NO) - by default +// bar.SetUnits(U_BYTES) - for Mb, Kb, etc +func (pb *ProgressBar) SetUnits(units Units) *ProgressBar { + pb.Units = units + return pb +} + +// Set max width, if width is bigger than terminal width, will be ignored +func (pb *ProgressBar) SetMaxWidth(width int) *ProgressBar { + pb.Width = width + pb.ForceWidth = false + return pb +} + +// Set bar width +func (pb *ProgressBar) SetWidth(width int) *ProgressBar { + pb.Width = width + pb.ForceWidth = true + return pb +} + +// End print +func (pb *ProgressBar) Finish() { + //Protect multiple calls + pb.finishOnce.Do(func() { + close(pb.finish) + pb.write(atomic.LoadInt64(&pb.current)) + switch { + case pb.Output != nil: + fmt.Fprintln(pb.Output) + case !pb.NotPrint: + fmt.Println() + } + pb.isFinish = true + }) +} + +// End print and write string 'str' +func (pb *ProgressBar) FinishPrint(str string) { + pb.Finish() + if pb.Output != nil { + fmt.Fprintln(pb.Output, str) + } else { + fmt.Println(str) + } +} + +// implement io.Writer +func (pb *ProgressBar) Write(p []byte) (n int, err error) { + n = len(p) + pb.Add(n) + return +} + +// implement io.Reader +func (pb *ProgressBar) Read(p []byte) (n int, err error) { + n = len(p) + pb.Add(n) + return +} + +// Create new proxy reader over bar +// Takes io.Reader or io.ReadCloser +func (pb *ProgressBar) NewProxyReader(r io.Reader) *Reader { + return &Reader{r, pb} +} + +func (pb *ProgressBar) write(current int64) { + width := pb.GetWidth() + + var percentBox, countersBox, timeLeftBox, speedBox, barBox, end, out string + + // percents + if pb.ShowPercent { + var percent float64 + if pb.Total > 0 { + percent = float64(current) / (float64(pb.Total) / float64(100)) + } else { + percent = float64(current) / float64(100) + } + percentBox = fmt.Sprintf(" %6.02f%%", percent) + } + + // counters + if pb.ShowCounters { + current := Format(current).To(pb.Units).Width(pb.UnitsWidth) + if pb.Total > 0 { + total := Format(pb.Total).To(pb.Units).Width(pb.UnitsWidth) + countersBox = fmt.Sprintf(" %s / %s ", current, total) + } else { + countersBox = fmt.Sprintf(" %s / ? ", current) + } + } + + // time left + fromStart := time.Now().Sub(pb.startTime) + currentFromStart := current - pb.startValue + select { + case <-pb.finish: + if pb.ShowFinalTime { + var left time.Duration + left = (fromStart / time.Second) * time.Second + timeLeftBox = fmt.Sprintf(" %s", left.String()) + } + default: + if pb.ShowTimeLeft && currentFromStart > 0 { + perEntry := fromStart / time.Duration(currentFromStart) + var left time.Duration + if pb.Total > 0 { + left = time.Duration(pb.Total-currentFromStart) * perEntry + left = (left / time.Second) * time.Second + } else { + left = time.Duration(currentFromStart) * perEntry + left = (left / time.Second) * time.Second + } + timeLeft := Format(int64(left)).To(U_DURATION).String() + timeLeftBox = fmt.Sprintf(" %s", timeLeft) + } + } + + if len(timeLeftBox) < pb.TimeBoxWidth { + timeLeftBox = fmt.Sprintf("%s%s", strings.Repeat(" ", pb.TimeBoxWidth-len(timeLeftBox)), timeLeftBox) + } + + // speed + if pb.ShowSpeed && currentFromStart > 0 { + fromStart := time.Now().Sub(pb.startTime) + speed := float64(currentFromStart) / (float64(fromStart) / float64(time.Second)) + speedBox = " " + Format(int64(speed)).To(pb.Units).Width(pb.UnitsWidth).PerSec().String() + } + + barWidth := escapeAwareRuneCountInString(countersBox + pb.BarStart + pb.BarEnd + percentBox + timeLeftBox + speedBox + pb.prefix + pb.postfix) + // bar + if pb.ShowBar { + size := width - barWidth + if size > 0 { + if pb.Total > 0 { + curCount := int(math.Ceil((float64(current) / float64(pb.Total)) * float64(size))) + emptCount := size - curCount + barBox = pb.BarStart + if emptCount < 0 { + emptCount = 0 + } + if curCount > size { + curCount = size + } + if emptCount <= 0 { + barBox += strings.Repeat(pb.Current, curCount) + } else if curCount > 0 { + barBox += strings.Repeat(pb.Current, curCount-1) + pb.CurrentN + } + barBox += strings.Repeat(pb.Empty, emptCount) + pb.BarEnd + } else { + barBox = pb.BarStart + pos := size - int(current)%int(size) + if pos-1 > 0 { + barBox += strings.Repeat(pb.Empty, pos-1) + } + barBox += pb.Current + if size-pos-1 > 0 { + barBox += strings.Repeat(pb.Empty, size-pos-1) + } + barBox += pb.BarEnd + } + } + } + + // check len + out = pb.prefix + countersBox + barBox + percentBox + speedBox + timeLeftBox + pb.postfix + if escapeAwareRuneCountInString(out) < width { + end = strings.Repeat(" ", width-utf8.RuneCountInString(out)) + } + + // and print! + pb.mu.Lock() + pb.lastPrint = out + end + pb.mu.Unlock() + switch { + case pb.isFinish: + return + case pb.Output != nil: + fmt.Fprint(pb.Output, "\r"+out+end) + case pb.Callback != nil: + pb.Callback(out + end) + case !pb.NotPrint: + fmt.Print("\r" + out + end) + } +} + +// GetTerminalWidth - returns terminal width for all platforms. +func GetTerminalWidth() (int, error) { + return terminalWidth() +} + +func (pb *ProgressBar) GetWidth() int { + if pb.ForceWidth { + return pb.Width + } + + width := pb.Width + termWidth, _ := terminalWidth() + if width == 0 || termWidth <= width { + width = termWidth + } + + return width +} + +// Write the current state of the progressbar +func (pb *ProgressBar) Update() { + c := atomic.LoadInt64(&pb.current) + if pb.AlwaysUpdate || c != pb.currentValue { + pb.write(c) + pb.currentValue = c + } + if pb.AutoStat { + if c == 0 { + pb.startTime = time.Now() + pb.startValue = 0 + } else if c >= pb.Total && pb.isFinish != true { + pb.Finish() + } + } +} + +func (pb *ProgressBar) String() string { + return pb.lastPrint +} + +// Internal loop for refreshing the progressbar +func (pb *ProgressBar) refresher() { + for { + select { + case <-pb.finish: + return + case <-time.After(pb.RefreshRate): + pb.Update() + } + } +} + +type window struct { + Row uint16 + Col uint16 + Xpixel uint16 + Ypixel uint16 +} diff --git a/vendor/gopkg.in/cheggaaa/pb.v1/pb_appengine.go b/vendor/gopkg.in/cheggaaa/pb.v1/pb_appengine.go new file mode 100644 index 0000000..d85dbc3 --- /dev/null +++ b/vendor/gopkg.in/cheggaaa/pb.v1/pb_appengine.go @@ -0,0 +1,11 @@ +// +build appengine + +package pb + +import "errors" + +// terminalWidth returns width of the terminal, which is not supported +// and should always failed on appengine classic which is a sandboxed PaaS. +func terminalWidth() (int, error) { + return 0, errors.New("Not supported") +} diff --git a/vendor/gopkg.in/cheggaaa/pb.v1/pb_nix.go b/vendor/gopkg.in/cheggaaa/pb.v1/pb_nix.go new file mode 100644 index 0000000..c06097b --- /dev/null +++ b/vendor/gopkg.in/cheggaaa/pb.v1/pb_nix.go @@ -0,0 +1,8 @@ +// +build linux darwin freebsd netbsd openbsd dragonfly +// +build !appengine + +package pb + +import "syscall" + +const sysIoctl = syscall.SYS_IOCTL diff --git a/vendor/gopkg.in/cheggaaa/pb.v1/pb_solaris.go b/vendor/gopkg.in/cheggaaa/pb.v1/pb_solaris.go new file mode 100644 index 0000000..b7d461e --- /dev/null +++ b/vendor/gopkg.in/cheggaaa/pb.v1/pb_solaris.go @@ -0,0 +1,6 @@ +// +build solaris +// +build !appengine + +package pb + +const sysIoctl = 54 diff --git a/vendor/gopkg.in/cheggaaa/pb.v1/pb_win.go b/vendor/gopkg.in/cheggaaa/pb.v1/pb_win.go new file mode 100644 index 0000000..72f6828 --- /dev/null +++ b/vendor/gopkg.in/cheggaaa/pb.v1/pb_win.go @@ -0,0 +1,141 @@ +// +build windows + +package pb + +import ( + "errors" + "fmt" + "os" + "sync" + "syscall" + "unsafe" +) + +var tty = os.Stdin + +var ( + kernel32 = syscall.NewLazyDLL("kernel32.dll") + + // GetConsoleScreenBufferInfo retrieves information about the + // specified console screen buffer. + // http://msdn.microsoft.com/en-us/library/windows/desktop/ms683171(v=vs.85).aspx + procGetConsoleScreenBufferInfo = kernel32.NewProc("GetConsoleScreenBufferInfo") + + // GetConsoleMode retrieves the current input mode of a console's + // input buffer or the current output mode of a console screen buffer. + // https://msdn.microsoft.com/en-us/library/windows/desktop/ms683167(v=vs.85).aspx + getConsoleMode = kernel32.NewProc("GetConsoleMode") + + // SetConsoleMode sets the input mode of a console's input buffer + // or the output mode of a console screen buffer. + // https://msdn.microsoft.com/en-us/library/windows/desktop/ms686033(v=vs.85).aspx + setConsoleMode = kernel32.NewProc("SetConsoleMode") + + // SetConsoleCursorPosition sets the cursor position in the + // specified console screen buffer. + // https://msdn.microsoft.com/en-us/library/windows/desktop/ms686025(v=vs.85).aspx + setConsoleCursorPosition = kernel32.NewProc("SetConsoleCursorPosition") +) + +type ( + // Defines the coordinates of the upper left and lower right corners + // of a rectangle. + // See + // http://msdn.microsoft.com/en-us/library/windows/desktop/ms686311(v=vs.85).aspx + smallRect struct { + Left, Top, Right, Bottom int16 + } + + // Defines the coordinates of a character cell in a console screen + // buffer. The origin of the coordinate system (0,0) is at the top, left cell + // of the buffer. + // See + // http://msdn.microsoft.com/en-us/library/windows/desktop/ms682119(v=vs.85).aspx + coordinates struct { + X, Y int16 + } + + word int16 + + // Contains information about a console screen buffer. + // http://msdn.microsoft.com/en-us/library/windows/desktop/ms682093(v=vs.85).aspx + consoleScreenBufferInfo struct { + dwSize coordinates + dwCursorPosition coordinates + wAttributes word + srWindow smallRect + dwMaximumWindowSize coordinates + } +) + +// terminalWidth returns width of the terminal. +func terminalWidth() (width int, err error) { + var info consoleScreenBufferInfo + _, _, e := syscall.Syscall(procGetConsoleScreenBufferInfo.Addr(), 2, uintptr(syscall.Stdout), uintptr(unsafe.Pointer(&info)), 0) + if e != 0 { + return 0, error(e) + } + return int(info.dwSize.X) - 1, nil +} + +func getCursorPos() (pos coordinates, err error) { + var info consoleScreenBufferInfo + _, _, e := syscall.Syscall(procGetConsoleScreenBufferInfo.Addr(), 2, uintptr(syscall.Stdout), uintptr(unsafe.Pointer(&info)), 0) + if e != 0 { + return info.dwCursorPosition, error(e) + } + return info.dwCursorPosition, nil +} + +func setCursorPos(pos coordinates) error { + _, _, e := syscall.Syscall(setConsoleCursorPosition.Addr(), 2, uintptr(syscall.Stdout), uintptr(uint32(uint16(pos.Y))<<16|uint32(uint16(pos.X))), 0) + if e != 0 { + return error(e) + } + return nil +} + +var ErrPoolWasStarted = errors.New("Bar pool was started") + +var echoLocked bool +var echoLockMutex sync.Mutex + +var oldState word + +func lockEcho() (quit chan int, err error) { + echoLockMutex.Lock() + defer echoLockMutex.Unlock() + if echoLocked { + err = ErrPoolWasStarted + return + } + echoLocked = true + + if _, _, e := syscall.Syscall(getConsoleMode.Addr(), 2, uintptr(syscall.Stdout), uintptr(unsafe.Pointer(&oldState)), 0); e != 0 { + err = fmt.Errorf("Can't get terminal settings: %v", e) + return + } + + newState := oldState + const ENABLE_ECHO_INPUT = 0x0004 + const ENABLE_LINE_INPUT = 0x0002 + newState = newState & (^(ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT)) + if _, _, e := syscall.Syscall(setConsoleMode.Addr(), 2, uintptr(syscall.Stdout), uintptr(newState), 0); e != 0 { + err = fmt.Errorf("Can't set terminal settings: %v", e) + return + } + return +} + +func unlockEcho() (err error) { + echoLockMutex.Lock() + defer echoLockMutex.Unlock() + if !echoLocked { + return + } + echoLocked = false + if _, _, e := syscall.Syscall(setConsoleMode.Addr(), 2, uintptr(syscall.Stdout), uintptr(oldState), 0); e != 0 { + err = fmt.Errorf("Can't set terminal settings") + } + return +} diff --git a/vendor/gopkg.in/cheggaaa/pb.v1/pb_x.go b/vendor/gopkg.in/cheggaaa/pb.v1/pb_x.go new file mode 100644 index 0000000..12e6fe6 --- /dev/null +++ b/vendor/gopkg.in/cheggaaa/pb.v1/pb_x.go @@ -0,0 +1,110 @@ +// +build linux darwin freebsd netbsd openbsd solaris dragonfly +// +build !appengine + +package pb + +import ( + "errors" + "fmt" + "os" + "os/signal" + "runtime" + "sync" + "syscall" + "unsafe" +) + +const ( + TIOCGWINSZ = 0x5413 + TIOCGWINSZ_OSX = 1074295912 +) + +var tty *os.File + +var ErrPoolWasStarted = errors.New("Bar pool was started") + +var echoLocked bool +var echoLockMutex sync.Mutex + +func init() { + var err error + tty, err = os.Open("/dev/tty") + if err != nil { + tty = os.Stdin + } +} + +// terminalWidth returns width of the terminal. +func terminalWidth() (int, error) { + w := new(window) + tio := syscall.TIOCGWINSZ + if runtime.GOOS == "darwin" { + tio = TIOCGWINSZ_OSX + } + res, _, err := syscall.Syscall(sysIoctl, + tty.Fd(), + uintptr(tio), + uintptr(unsafe.Pointer(w)), + ) + if int(res) == -1 { + return 0, err + } + return int(w.Col), nil +} + +var oldState syscall.Termios + +func lockEcho() (quit chan int, err error) { + echoLockMutex.Lock() + defer echoLockMutex.Unlock() + if echoLocked { + err = ErrPoolWasStarted + return + } + echoLocked = true + + fd := tty.Fd() + if _, _, e := syscall.Syscall6(sysIoctl, fd, ioctlReadTermios, uintptr(unsafe.Pointer(&oldState)), 0, 0, 0); e != 0 { + err = fmt.Errorf("Can't get terminal settings: %v", e) + return + } + + newState := oldState + newState.Lflag &^= syscall.ECHO + newState.Lflag |= syscall.ICANON | syscall.ISIG + newState.Iflag |= syscall.ICRNL + if _, _, e := syscall.Syscall6(sysIoctl, fd, ioctlWriteTermios, uintptr(unsafe.Pointer(&newState)), 0, 0, 0); e != 0 { + err = fmt.Errorf("Can't set terminal settings: %v", e) + return + } + quit = make(chan int, 1) + go catchTerminate(quit) + return +} + +func unlockEcho() (err error) { + echoLockMutex.Lock() + defer echoLockMutex.Unlock() + if !echoLocked { + return + } + echoLocked = false + fd := tty.Fd() + if _, _, e := syscall.Syscall6(sysIoctl, fd, ioctlWriteTermios, uintptr(unsafe.Pointer(&oldState)), 0, 0, 0); e != 0 { + err = fmt.Errorf("Can't set terminal settings") + } + return +} + +// listen exit signals and restore terminal state +func catchTerminate(quit chan int) { + sig := make(chan os.Signal, 1) + signal.Notify(sig, os.Interrupt, syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGKILL) + defer signal.Stop(sig) + select { + case <-quit: + unlockEcho() + case <-sig: + unlockEcho() + } +} diff --git a/vendor/gopkg.in/cheggaaa/pb.v1/pool.go b/vendor/gopkg.in/cheggaaa/pb.v1/pool.go new file mode 100644 index 0000000..0b4a4af --- /dev/null +++ b/vendor/gopkg.in/cheggaaa/pb.v1/pool.go @@ -0,0 +1,76 @@ +// +build linux darwin freebsd netbsd openbsd solaris dragonfly windows + +package pb + +import ( + "sync" + "time" +) + +// Create and start new pool with given bars +// You need call pool.Stop() after work +func StartPool(pbs ...*ProgressBar) (pool *Pool, err error) { + pool = new(Pool) + if err = pool.start(); err != nil { + return + } + pool.Add(pbs...) + return +} + +type Pool struct { + RefreshRate time.Duration + bars []*ProgressBar + quit chan int + finishOnce sync.Once +} + +// Add progress bars. +func (p *Pool) Add(pbs ...*ProgressBar) { + for _, bar := range pbs { + bar.ManualUpdate = true + bar.NotPrint = true + bar.Start() + p.bars = append(p.bars, bar) + } +} + +func (p *Pool) start() (err error) { + p.RefreshRate = DefaultRefreshRate + quit, err := lockEcho() + if err != nil { + return + } + p.quit = make(chan int) + go p.writer(quit) + return +} + +func (p *Pool) writer(finish chan int) { + var first = true + for { + select { + case <-time.After(p.RefreshRate): + if p.print(first) { + p.print(false) + finish <- 1 + return + } + first = false + case <-p.quit: + finish <- 1 + return + } + } +} + +// Restore terminal state and close pool +func (p *Pool) Stop() error { + // Wait until one final refresh has passed. + time.Sleep(p.RefreshRate) + + p.finishOnce.Do(func() { + close(p.quit) + }) + return unlockEcho() +} diff --git a/vendor/gopkg.in/cheggaaa/pb.v1/pool_win.go b/vendor/gopkg.in/cheggaaa/pb.v1/pool_win.go new file mode 100644 index 0000000..d7a5ace --- /dev/null +++ b/vendor/gopkg.in/cheggaaa/pb.v1/pool_win.go @@ -0,0 +1,35 @@ +// +build windows + +package pb + +import ( + "fmt" + "log" +) + +func (p *Pool) print(first bool) bool { + var out string + if !first { + coords, err := getCursorPos() + if err != nil { + log.Panic(err) + } + coords.Y -= int16(len(p.bars)) + coords.X = 0 + + err = setCursorPos(coords) + if err != nil { + log.Panic(err) + } + } + isFinished := true + for _, bar := range p.bars { + if !bar.isFinish { + isFinished = false + } + bar.Update() + out += fmt.Sprintf("\r%s\n", bar.String()) + } + fmt.Print(out) + return isFinished +} diff --git a/vendor/gopkg.in/cheggaaa/pb.v1/pool_x.go b/vendor/gopkg.in/cheggaaa/pb.v1/pool_x.go new file mode 100644 index 0000000..d95b71d --- /dev/null +++ b/vendor/gopkg.in/cheggaaa/pb.v1/pool_x.go @@ -0,0 +1,22 @@ +// +build linux darwin freebsd netbsd openbsd solaris dragonfly + +package pb + +import "fmt" + +func (p *Pool) print(first bool) bool { + var out string + if !first { + out = fmt.Sprintf("\033[%dA", len(p.bars)) + } + isFinished := true + for _, bar := range p.bars { + if !bar.isFinish { + isFinished = false + } + bar.Update() + out += fmt.Sprintf("\r%s\n", bar.String()) + } + fmt.Print(out) + return isFinished +} diff --git a/vendor/gopkg.in/cheggaaa/pb.v1/reader.go b/vendor/gopkg.in/cheggaaa/pb.v1/reader.go new file mode 100644 index 0000000..9f3148b --- /dev/null +++ b/vendor/gopkg.in/cheggaaa/pb.v1/reader.go @@ -0,0 +1,25 @@ +package pb + +import ( + "io" +) + +// It's proxy reader, implement io.Reader +type Reader struct { + io.Reader + bar *ProgressBar +} + +func (r *Reader) Read(p []byte) (n int, err error) { + n, err = r.Reader.Read(p) + r.bar.Add(n) + return +} + +// Close the reader when it implements io.Closer +func (r *Reader) Close() (err error) { + if closer, ok := r.Reader.(io.Closer); ok { + return closer.Close() + } + return +} diff --git a/vendor/gopkg.in/cheggaaa/pb.v1/runecount.go b/vendor/gopkg.in/cheggaaa/pb.v1/runecount.go new file mode 100644 index 0000000..d52edd3 --- /dev/null +++ b/vendor/gopkg.in/cheggaaa/pb.v1/runecount.go @@ -0,0 +1,17 @@ +package pb + +import ( + "github.com/mattn/go-runewidth" + "regexp" +) + +// Finds the control character sequences (like colors) +var ctrlFinder = regexp.MustCompile("\x1b\x5b[0-9]+\x6d") + +func escapeAwareRuneCountInString(s string) int { + n := runewidth.StringWidth(s) + for _, sm := range ctrlFinder.FindAllString(s, -1) { + n -= len(sm) + } + return n +} diff --git a/vendor/gopkg.in/cheggaaa/pb.v1/termios_bsd.go b/vendor/gopkg.in/cheggaaa/pb.v1/termios_bsd.go new file mode 100644 index 0000000..517ea8e --- /dev/null +++ b/vendor/gopkg.in/cheggaaa/pb.v1/termios_bsd.go @@ -0,0 +1,9 @@ +// +build darwin freebsd netbsd openbsd dragonfly +// +build !appengine + +package pb + +import "syscall" + +const ioctlReadTermios = syscall.TIOCGETA +const ioctlWriteTermios = syscall.TIOCSETA diff --git a/vendor/gopkg.in/cheggaaa/pb.v1/termios_nix.go b/vendor/gopkg.in/cheggaaa/pb.v1/termios_nix.go new file mode 100644 index 0000000..ebb3fe8 --- /dev/null +++ b/vendor/gopkg.in/cheggaaa/pb.v1/termios_nix.go @@ -0,0 +1,7 @@ +// +build linux solaris +// +build !appengine + +package pb + +const ioctlReadTermios = 0x5401 // syscall.TCGETS +const ioctlWriteTermios = 0x5402 // syscall.TCSETS diff --git a/vendor/gopkg.in/go-playground/validator.v8/README.md b/vendor/gopkg.in/go-playground/validator.v8/README.md index dd2a4f4..7583259 100644 --- a/vendor/gopkg.in/go-playground/validator.v8/README.md +++ b/vendor/gopkg.in/go-playground/validator.v8/README.md @@ -2,10 +2,10 @@ Package validator ================ [![Join the chat at https://gitter.im/bluesuncorp/validator](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/go-playground/validator?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) -![Project status](https://img.shields.io/badge/version-8.17.1-green.svg) +![Project status](https://img.shields.io/badge/version-8.18.1-green.svg) [![Build Status](https://semaphoreci.com/api/v1/projects/ec20115f-ef1b-4c7d-9393-cc76aba74eb4/530054/badge.svg)](https://semaphoreci.com/joeybloggs/validator) [![Coverage Status](https://coveralls.io/repos/go-playground/validator/badge.svg?branch=v8&service=github)](https://coveralls.io/github/go-playground/validator?branch=v8) -[![Go Report Card](http://goreportcard.com/badge/go-playground/validator)](http://goreportcard.com/report/go-playground/validator) +[![Go Report Card](https://goreportcard.com/badge/github.com/go-playground/validator)](https://goreportcard.com/report/github.com/go-playground/validator) [![GoDoc](https://godoc.org/gopkg.in/go-playground/validator.v8?status.svg)](https://godoc.org/gopkg.in/go-playground/validator.v8) ![License](https://img.shields.io/dub/l/vibe-d.svg) @@ -310,36 +310,35 @@ Benchmarks ------ ###### Run on MacBook Pro (Retina, 15-inch, Late 2013) 2.6 GHz Intel Core i7 16 GB 1600 MHz DDR3 using Go version go1.5.3 darwin/amd64 ```go -go test -cpu=4 -bench=. -benchmem=true PASS -BenchmarkFieldSuccess-4 10000000 167 ns/op 0 B/op 0 allocs/op -BenchmarkFieldFailure-4 2000000 701 ns/op 432 B/op 4 allocs/op -BenchmarkFieldDiveSuccess-4 500000 2937 ns/op 480 B/op 27 allocs/op -BenchmarkFieldDiveFailure-4 500000 3536 ns/op 912 B/op 31 allocs/op -BenchmarkFieldCustomTypeSuccess-4 5000000 341 ns/op 32 B/op 2 allocs/op -BenchmarkFieldCustomTypeFailure-4 2000000 679 ns/op 432 B/op 4 allocs/op -BenchmarkFieldOrTagSuccess-4 1000000 1157 ns/op 16 B/op 1 allocs/op -BenchmarkFieldOrTagFailure-4 1000000 1109 ns/op 464 B/op 6 allocs/op -BenchmarkStructLevelValidationSuccess-4 2000000 694 ns/op 176 B/op 6 allocs/op -BenchmarkStructLevelValidationFailure-4 1000000 1311 ns/op 640 B/op 11 allocs/op -BenchmarkStructSimpleCustomTypeSuccess-4 2000000 894 ns/op 80 B/op 5 allocs/op -BenchmarkStructSimpleCustomTypeFailure-4 1000000 1496 ns/op 688 B/op 11 allocs/op -BenchmarkStructPartialSuccess-4 1000000 1229 ns/op 384 B/op 10 allocs/op -BenchmarkStructPartialFailure-4 1000000 1838 ns/op 832 B/op 15 allocs/op -BenchmarkStructExceptSuccess-4 2000000 961 ns/op 336 B/op 7 allocs/op -BenchmarkStructExceptFailure-4 1000000 1218 ns/op 384 B/op 10 allocs/op -BenchmarkStructSimpleCrossFieldSuccess-4 2000000 954 ns/op 128 B/op 6 allocs/op -BenchmarkStructSimpleCrossFieldFailure-4 1000000 1569 ns/op 592 B/op 11 allocs/op -BenchmarkStructSimpleCrossStructCrossFieldSuccess-4 1000000 1588 ns/op 192 B/op 10 allocs/op -BenchmarkStructSimpleCrossStructCrossFieldFailure-4 1000000 2217 ns/op 656 B/op 15 allocs/op -BenchmarkStructSimpleSuccess-4 2000000 925 ns/op 48 B/op 3 allocs/op -BenchmarkStructSimpleFailure-4 1000000 1650 ns/op 688 B/op 11 allocs/op -BenchmarkStructSimpleSuccessParallel-4 5000000 261 ns/op 48 B/op 3 allocs/op -BenchmarkStructSimpleFailureParallel-4 2000000 758 ns/op 688 B/op 11 allocs/op -BenchmarkStructComplexSuccess-4 300000 5868 ns/op 544 B/op 32 allocs/op -BenchmarkStructComplexFailure-4 200000 10767 ns/op 3912 B/op 77 allocs/op -BenchmarkStructComplexSuccessParallel-4 1000000 1559 ns/op 544 B/op 32 allocs/op -BenchmarkStructComplexFailureParallel-4 500000 3747 ns/op 3912 B/op 77 allocs +BenchmarkFieldSuccess-8 20000000 118 ns/op 0 B/op 0 allocs/op +BenchmarkFieldFailure-8 2000000 758 ns/op 432 B/op 4 allocs/op +BenchmarkFieldDiveSuccess-8 500000 2471 ns/op 464 B/op 28 allocs/op +BenchmarkFieldDiveFailure-8 500000 3172 ns/op 896 B/op 32 allocs/op +BenchmarkFieldCustomTypeSuccess-8 5000000 300 ns/op 32 B/op 2 allocs/op +BenchmarkFieldCustomTypeFailure-8 2000000 775 ns/op 432 B/op 4 allocs/op +BenchmarkFieldOrTagSuccess-8 1000000 1122 ns/op 4 B/op 1 allocs/op +BenchmarkFieldOrTagFailure-8 1000000 1167 ns/op 448 B/op 6 allocs/op +BenchmarkStructLevelValidationSuccess-8 3000000 548 ns/op 160 B/op 5 allocs/op +BenchmarkStructLevelValidationFailure-8 3000000 558 ns/op 160 B/op 5 allocs/op +BenchmarkStructSimpleCustomTypeSuccess-8 2000000 623 ns/op 36 B/op 3 allocs/op +BenchmarkStructSimpleCustomTypeFailure-8 1000000 1381 ns/op 640 B/op 9 allocs/op +BenchmarkStructPartialSuccess-8 1000000 1036 ns/op 272 B/op 9 allocs/op +BenchmarkStructPartialFailure-8 1000000 1734 ns/op 730 B/op 14 allocs/op +BenchmarkStructExceptSuccess-8 2000000 888 ns/op 250 B/op 7 allocs/op +BenchmarkStructExceptFailure-8 1000000 1036 ns/op 272 B/op 9 allocs/op +BenchmarkStructSimpleCrossFieldSuccess-8 2000000 773 ns/op 80 B/op 4 allocs/op +BenchmarkStructSimpleCrossFieldFailure-8 1000000 1487 ns/op 536 B/op 9 allocs/op +BenchmarkStructSimpleCrossStructCrossFieldSuccess-8 1000000 1261 ns/op 112 B/op 7 allocs/op +BenchmarkStructSimpleCrossStructCrossFieldFailure-8 1000000 2055 ns/op 576 B/op 12 allocs/op +BenchmarkStructSimpleSuccess-8 3000000 519 ns/op 4 B/op 1 allocs/op +BenchmarkStructSimpleFailure-8 1000000 1429 ns/op 640 B/op 9 allocs/op +BenchmarkStructSimpleSuccessParallel-8 10000000 146 ns/op 4 B/op 1 allocs/op +BenchmarkStructSimpleFailureParallel-8 2000000 551 ns/op 640 B/op 9 allocs/op +BenchmarkStructComplexSuccess-8 500000 3269 ns/op 244 B/op 15 allocs/op +BenchmarkStructComplexFailure-8 200000 8436 ns/op 3609 B/op 60 allocs/op +BenchmarkStructComplexSuccessParallel-8 1000000 1024 ns/op 244 B/op 15 allocs/op +BenchmarkStructComplexFailureParallel-8 500000 3536 ns/op 3609 B/op 60 allocs/op ``` Complimentary Software diff --git a/vendor/gopkg.in/go-playground/validator.v8/baked_in.go b/vendor/gopkg.in/go-playground/validator.v8/baked_in.go index 3dcb0de..44aaa08 100644 --- a/vendor/gopkg.in/go-playground/validator.v8/baked_in.go +++ b/vendor/gopkg.in/go-playground/validator.v8/baked_in.go @@ -271,11 +271,7 @@ func IsISBN13(v *Validate, topStruct reflect.Value, currentStructOrField reflect checksum += factor[i%2] * int32(s[i]-'0') } - if (int32(s[12]-'0'))-((10-(checksum%10))%10) == 0 { - return true - } - - return false + return (int32(s[12]-'0'))-((10-(checksum%10))%10) == 0 } // IsISBN10 is the validation function for validating if the field's value is a valid v10 ISBN. @@ -301,32 +297,28 @@ func IsISBN10(v *Validate, topStruct reflect.Value, currentStructOrField reflect checksum += 10 * int32(s[9]-'0') } - if checksum%11 == 0 { - return true - } - - return false + return checksum%11 == 0 } -// ExcludesRune is the validation function for validating that the field's value does not contain the rune specified withing the param. +// ExcludesRune is the validation function for validating that the field's value does not contain the rune specified within the param. // NOTE: This is exposed for use within your own custom functions and not intended to be called directly. func ExcludesRune(v *Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool { return !ContainsRune(v, topStruct, currentStructOrField, field, fieldType, fieldKind, param) } -// ExcludesAll is the validation function for validating that the field's value does not contain any of the characters specified withing the param. +// ExcludesAll is the validation function for validating that the field's value does not contain any of the characters specified within the param. // NOTE: This is exposed for use within your own custom functions and not intended to be called directly. func ExcludesAll(v *Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool { return !ContainsAny(v, topStruct, currentStructOrField, field, fieldType, fieldKind, param) } -// Excludes is the validation function for validating that the field's value does not contain the text specified withing the param. +// Excludes is the validation function for validating that the field's value does not contain the text specified within the param. // NOTE: This is exposed for use within your own custom functions and not intended to be called directly. func Excludes(v *Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool { return !Contains(v, topStruct, currentStructOrField, field, fieldType, fieldKind, param) } -// ContainsRune is the validation function for validating that the field's value contains the rune specified withing the param. +// ContainsRune is the validation function for validating that the field's value contains the rune specified within the param. // NOTE: This is exposed for use within your own custom functions and not intended to be called directly. func ContainsRune(v *Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool { r, _ := utf8.DecodeRuneInString(param) @@ -334,13 +326,13 @@ func ContainsRune(v *Validate, topStruct reflect.Value, currentStructOrField ref return strings.ContainsRune(field.String(), r) } -// ContainsAny is the validation function for validating that the field's value contains any of the characters specified withing the param. +// ContainsAny is the validation function for validating that the field's value contains any of the characters specified within the param. // NOTE: This is exposed for use within your own custom functions and not intended to be called directly. func ContainsAny(v *Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool { return strings.ContainsAny(field.String(), param) } -// Contains is the validation function for validating that the field's value contains the text specified withing the param. +// Contains is the validation function for validating that the field's value contains the text specified within the param. // NOTE: This is exposed for use within your own custom functions and not intended to be called directly. func Contains(v *Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool { return strings.Contains(field.String(), param) @@ -1040,7 +1032,7 @@ func IsGt(v *Validate, topStruct reflect.Value, currentStructOrField reflect.Val return field.Float() > p case reflect.Struct: - if field.Type() == timeType || field.Type() == timePtrType { + if fieldType == timeType || fieldType == timePtrType { return field.Interface().(time.Time).After(time.Now().UTC()) } @@ -1255,7 +1247,7 @@ func IsLt(v *Validate, topStruct reflect.Value, currentStructOrField reflect.Val case reflect.Struct: - if field.Type() == timeType || field.Type() == timePtrType { + if fieldType == timeType || fieldType == timePtrType { return field.Interface().(time.Time).Before(time.Now().UTC()) } diff --git a/vendor/gopkg.in/go-playground/validator.v8/cache.go b/vendor/gopkg.in/go-playground/validator.v8/cache.go index 289226e..76670c1 100644 --- a/vendor/gopkg.in/go-playground/validator.v8/cache.go +++ b/vendor/gopkg.in/go-playground/validator.v8/cache.go @@ -1,71 +1,263 @@ package validator import ( + "fmt" "reflect" + "strings" "sync" + "sync/atomic" ) -type cachedField struct { - Idx int - Name string - AltName string - CachedTag *cachedTag +type tagType uint8 + +const ( + typeDefault tagType = iota + typeOmitEmpty + typeNoStructLevel + typeStructOnly + typeDive + typeOr + typeExists +) + +type structCache struct { + lock sync.Mutex + m atomic.Value // map[reflect.Type]*cStruct } -type cachedStruct struct { - Name string - fields map[int]cachedField +func (sc *structCache) Get(key reflect.Type) (c *cStruct, found bool) { + c, found = sc.m.Load().(map[reflect.Type]*cStruct)[key] + return +} + +func (sc *structCache) Set(key reflect.Type, value *cStruct) { + + m := sc.m.Load().(map[reflect.Type]*cStruct) + + nm := make(map[reflect.Type]*cStruct, len(m)+1) + for k, v := range m { + nm[k] = v + } + nm[key] = value + sc.m.Store(nm) } -type structCacheMap struct { - lock sync.RWMutex - m map[reflect.Type]*cachedStruct +type tagCache struct { + lock sync.Mutex + m atomic.Value // map[string]*cTag } -func (s *structCacheMap) Get(key reflect.Type) (*cachedStruct, bool) { - s.lock.RLock() - value, ok := s.m[key] - s.lock.RUnlock() - return value, ok +func (tc *tagCache) Get(key string) (c *cTag, found bool) { + c, found = tc.m.Load().(map[string]*cTag)[key] + return } -func (s *structCacheMap) Set(key reflect.Type, value *cachedStruct) { - s.lock.Lock() - s.m[key] = value - s.lock.Unlock() +func (tc *tagCache) Set(key string, value *cTag) { + + m := tc.m.Load().(map[string]*cTag) + + nm := make(map[string]*cTag, len(m)+1) + for k, v := range m { + nm[k] = v + } + nm[key] = value + tc.m.Store(nm) } -type cachedTag struct { - tag string - isOmitEmpty bool - isNoStructLevel bool - isStructOnly bool - diveTag string - tags []*tagVals +type cStruct struct { + Name string + fields map[int]*cField + fn StructLevelFunc } -type tagVals struct { - tagVals [][]string - isOrVal bool - isAlias bool - tag string +type cField struct { + Idx int + Name string + AltName string + cTags *cTag } -type tagCacheMap struct { - lock sync.RWMutex - m map[string]*cachedTag +type cTag struct { + tag string + aliasTag string + actualAliasTag string + param string + hasAlias bool + typeof tagType + hasTag bool + fn Func + next *cTag } -func (s *tagCacheMap) Get(key string) (*cachedTag, bool) { - s.lock.RLock() - value, ok := s.m[key] - s.lock.RUnlock() +func (v *Validate) extractStructCache(current reflect.Value, sName string) *cStruct { + + v.structCache.lock.Lock() + defer v.structCache.lock.Unlock() // leave as defer! because if inner panics, it will never get unlocked otherwise! + + typ := current.Type() + + // could have been multiple trying to access, but once first is done this ensures struct + // isn't parsed again. + cs, ok := v.structCache.Get(typ) + if ok { + return cs + } + + cs = &cStruct{Name: sName, fields: make(map[int]*cField), fn: v.structLevelFuncs[typ]} + + numFields := current.NumField() + + var ctag *cTag + var fld reflect.StructField + var tag string + var customName string + + for i := 0; i < numFields; i++ { + + fld = typ.Field(i) + + if !fld.Anonymous && fld.PkgPath != blank { + continue + } + + tag = fld.Tag.Get(v.tagName) + + if tag == skipValidationTag { + continue + } + + customName = fld.Name + + if v.fieldNameTag != blank { + + name := strings.SplitN(fld.Tag.Get(v.fieldNameTag), ",", 2)[0] + + // dash check is for json "-" (aka skipValidationTag) means don't output in json + if name != "" && name != skipValidationTag { + customName = name + } + } + + // NOTE: cannot use shared tag cache, because tags may be equal, but things like alias may be different + // and so only struct level caching can be used instead of combined with Field tag caching + + if len(tag) > 0 { + ctag, _ = v.parseFieldTagsRecursive(tag, fld.Name, blank, false) + } else { + // even if field doesn't have validations need cTag for traversing to potential inner/nested + // elements of the field. + ctag = new(cTag) + } - return value, ok + cs.fields[i] = &cField{Idx: i, Name: fld.Name, AltName: customName, cTags: ctag} + } + + v.structCache.Set(typ, cs) + + return cs } -func (s *tagCacheMap) Set(key string, value *cachedTag) { - s.lock.Lock() - s.m[key] = value - s.lock.Unlock() +func (v *Validate) parseFieldTagsRecursive(tag string, fieldName string, alias string, hasAlias bool) (firstCtag *cTag, current *cTag) { + + var t string + var ok bool + noAlias := len(alias) == 0 + tags := strings.Split(tag, tagSeparator) + + for i := 0; i < len(tags); i++ { + + t = tags[i] + + if noAlias { + alias = t + } + + if v.hasAliasValidators { + // check map for alias and process new tags, otherwise process as usual + if tagsVal, found := v.aliasValidators[t]; found { + + if i == 0 { + firstCtag, current = v.parseFieldTagsRecursive(tagsVal, fieldName, t, true) + } else { + next, curr := v.parseFieldTagsRecursive(tagsVal, fieldName, t, true) + current.next, current = next, curr + + } + + continue + } + } + + if i == 0 { + current = &cTag{aliasTag: alias, hasAlias: hasAlias, hasTag: true} + firstCtag = current + } else { + current.next = &cTag{aliasTag: alias, hasAlias: hasAlias, hasTag: true} + current = current.next + } + + switch t { + + case diveTag: + current.typeof = typeDive + continue + + case omitempty: + current.typeof = typeOmitEmpty + continue + + case structOnlyTag: + current.typeof = typeStructOnly + continue + + case noStructLevelTag: + current.typeof = typeNoStructLevel + continue + + case existsTag: + current.typeof = typeExists + continue + + default: + + // if a pipe character is needed within the param you must use the utf8Pipe representation "0x7C" + orVals := strings.Split(t, orSeparator) + + for j := 0; j < len(orVals); j++ { + + vals := strings.SplitN(orVals[j], tagKeySeparator, 2) + + if noAlias { + alias = vals[0] + current.aliasTag = alias + } else { + current.actualAliasTag = t + } + + if j > 0 { + current.next = &cTag{aliasTag: alias, actualAliasTag: current.actualAliasTag, hasAlias: hasAlias, hasTag: true} + current = current.next + } + + current.tag = vals[0] + if len(current.tag) == 0 { + panic(strings.TrimSpace(fmt.Sprintf(invalidValidation, fieldName))) + } + + if current.fn, ok = v.validationFuncs[current.tag]; !ok { + panic(strings.TrimSpace(fmt.Sprintf(undefinedValidation, fieldName))) + } + + if len(orVals) > 1 { + current.typeof = typeOr + } + + if len(vals) > 1 { + current.param = strings.Replace(strings.Replace(vals[1], utf8HexComma, ",", -1), utf8Pipe, "|", -1) + } + } + } + } + + return } diff --git a/vendor/gopkg.in/go-playground/validator.v8/doc.go b/vendor/gopkg.in/go-playground/validator.v8/doc.go index 90b129a..fdede2c 100644 --- a/vendor/gopkg.in/go-playground/validator.v8/doc.go +++ b/vendor/gopkg.in/go-playground/validator.v8/doc.go @@ -162,7 +162,7 @@ Here is a list of the current built in validators: Skip Field -Tells the validation to skip this struct field; this is particularily +Tells the validation to skip this struct field; this is particularly handy in ignoring embedded structs from being validated. (Usage: -) Usage: - diff --git a/vendor/gopkg.in/go-playground/validator.v8/util.go b/vendor/gopkg.in/go-playground/validator.v8/util.go index ce01c7c..e811579 100644 --- a/vendor/gopkg.in/go-playground/validator.v8/util.go +++ b/vendor/gopkg.in/go-playground/validator.v8/util.go @@ -1,14 +1,12 @@ package validator import ( - "fmt" "reflect" "strconv" "strings" ) const ( - dash = "-" blank = "" namespaceSeparator = "." leftBracket = "[" @@ -19,15 +17,15 @@ const ( ) var ( - restrictedTags = map[string]*struct{}{ - diveTag: emptyStructPtr, - existsTag: emptyStructPtr, - structOnlyTag: emptyStructPtr, - omitempty: emptyStructPtr, - skipValidationTag: emptyStructPtr, - utf8HexComma: emptyStructPtr, - utf8Pipe: emptyStructPtr, - noStructLevelTag: emptyStructPtr, + restrictedTags = map[string]struct{}{ + diveTag: {}, + existsTag: {}, + structOnlyTag: {}, + omitempty: {}, + skipValidationTag: {}, + utf8HexComma: {}, + utf8Pipe: {}, + noStructLevelTag: {}, } ) @@ -37,48 +35,54 @@ var ( // it is exposed for use within you Custom Functions func (v *Validate) ExtractType(current reflect.Value) (reflect.Value, reflect.Kind) { + val, k, _ := v.extractTypeInternal(current, false) + return val, k +} + +// only exists to not break backward compatibility, needed to return the third param for a bug fix internally +func (v *Validate) extractTypeInternal(current reflect.Value, nullable bool) (reflect.Value, reflect.Kind, bool) { + switch current.Kind() { case reflect.Ptr: + nullable = true + if current.IsNil() { - return current, reflect.Ptr + return current, reflect.Ptr, nullable } - return v.ExtractType(current.Elem()) + return v.extractTypeInternal(current.Elem(), nullable) case reflect.Interface: + nullable = true + if current.IsNil() { - return current, reflect.Interface + return current, reflect.Interface, nullable } - return v.ExtractType(current.Elem()) + return v.extractTypeInternal(current.Elem(), nullable) case reflect.Invalid: - return current, reflect.Invalid + return current, reflect.Invalid, nullable default: if v.hasCustomFuncs { - // fmt.Println("Type", current.Type()) - if fn, ok := v.customTypeFuncs[current.Type()]; ok { - - // fmt.Println("OK") - return v.ExtractType(reflect.ValueOf(fn(current))) + if fn, ok := v.customTypeFuncs[current.Type()]; ok { + return v.extractTypeInternal(reflect.ValueOf(fn(current)), nullable) } - - // fmt.Println("NOT OK") } - return current, current.Kind() + return current, current.Kind(), nullable } } // GetStructFieldOK traverses a struct to retrieve a specific field denoted by the provided namespace and // returns the field, field kind and whether is was successful in retrieving the field at all. // NOTE: when not successful ok will be false, this can happen when a nested struct is nil and so the field -// could not be retrived because it didnt exist. +// could not be retrieved because it didn't exist. func (v *Validate) GetStructFieldOK(current reflect.Value, namespace string) (reflect.Value, reflect.Kind, bool) { current, kind := v.ExtractType(current) @@ -112,7 +116,6 @@ func (v *Validate) GetStructFieldOK(current reflect.Value, namespace string) (re ns = namespace[idx+1:] } else { ns = blank - idx = len(namespace) } bracketIdx := strings.Index(fld, leftBracket) @@ -212,7 +215,7 @@ func (v *Validate) GetStructFieldOK(current reflect.Value, namespace string) (re panic("Invalid field namespace") } -// asInt retuns the parameter as a int64 +// asInt returns the parameter as a int64 // or panics if it can't convert func asInt(param string) int64 { @@ -247,136 +250,3 @@ func panicIf(err error) { panic(err.Error()) } } - -func (v *Validate) parseStruct(current reflect.Value, sName string) *cachedStruct { - - typ := current.Type() - s := &cachedStruct{Name: sName, fields: map[int]cachedField{}} - - numFields := current.NumField() - - var fld reflect.StructField - var tag string - var customName string - - for i := 0; i < numFields; i++ { - - fld = typ.Field(i) - - if fld.PkgPath != blank { - continue - } - - tag = fld.Tag.Get(v.tagName) - - if tag == skipValidationTag { - continue - } - - customName = fld.Name - if v.fieldNameTag != blank { - - name := strings.SplitN(fld.Tag.Get(v.fieldNameTag), ",", 2)[0] - - // dash check is for json "-" (aka skipValidationTag) means don't output in json - if name != "" && name != skipValidationTag { - customName = name - } - } - - cTag, ok := v.tagCache.Get(tag) - if !ok { - cTag = v.parseTags(tag, fld.Name) - } - - s.fields[i] = cachedField{Idx: i, Name: fld.Name, AltName: customName, CachedTag: cTag} - } - - v.structCache.Set(typ, s) - - return s -} - -func (v *Validate) parseTags(tag, fieldName string) *cachedTag { - - cTag := &cachedTag{tag: tag} - - v.parseTagsRecursive(cTag, tag, fieldName, blank, false) - - v.tagCache.Set(tag, cTag) - - return cTag -} - -func (v *Validate) parseTagsRecursive(cTag *cachedTag, tag, fieldName, alias string, isAlias bool) bool { - - if tag == blank { - return true - } - - for _, t := range strings.Split(tag, tagSeparator) { - - if v.hasAliasValidators { - // check map for alias and process new tags, otherwise process as usual - if tagsVal, ok := v.aliasValidators[t]; ok { - - leave := v.parseTagsRecursive(cTag, tagsVal, fieldName, t, true) - - if leave { - return leave - } - - continue - } - } - - switch t { - - case diveTag: - cTag.diveTag = tag - tVals := &tagVals{tagVals: [][]string{{t}}} - cTag.tags = append(cTag.tags, tVals) - return true - - case omitempty: - cTag.isOmitEmpty = true - - case structOnlyTag: - cTag.isStructOnly = true - - case noStructLevelTag: - cTag.isNoStructLevel = true - } - - // if a pipe character is needed within the param you must use the utf8Pipe representation "0x7C" - orVals := strings.Split(t, orSeparator) - tagVal := &tagVals{isAlias: isAlias, isOrVal: len(orVals) > 1, tagVals: make([][]string, len(orVals))} - cTag.tags = append(cTag.tags, tagVal) - - var key string - var param string - - for i, val := range orVals { - vals := strings.SplitN(val, tagKeySeparator, 2) - key = vals[0] - - tagVal.tag = key - - if isAlias { - tagVal.tag = alias - } - - if key == blank { - panic(strings.TrimSpace(fmt.Sprintf(invalidValidation, fieldName))) - } - - if len(vals) > 1 { - param = strings.Replace(strings.Replace(vals[1], utf8HexComma, ",", -1), utf8Pipe, "|", -1) - } - - tagVal.tagVals[i] = []string{key, param} - } - } - - return false -} diff --git a/vendor/gopkg.in/go-playground/validator.v8/validator.go b/vendor/gopkg.in/go-playground/validator.v8/validator.go index 0e6db7e..2b1d716 100644 --- a/vendor/gopkg.in/go-playground/validator.v8/validator.go +++ b/vendor/gopkg.in/go-playground/validator.v8/validator.go @@ -41,9 +41,9 @@ const ( ) var ( - timeType = reflect.TypeOf(time.Time{}) - timePtrType = reflect.TypeOf(&time.Time{}) - emptyStructPtr = new(struct{}) + timeType = reflect.TypeOf(time.Time{}) + timePtrType = reflect.TypeOf(&time.Time{}) + defaultCField = new(cField) ) // StructLevel contains all of the information and helper methods @@ -147,8 +147,8 @@ type Validate struct { hasCustomFuncs bool hasAliasValidators bool hasStructLevelFuncs bool - tagCache *tagCacheMap - structCache *structCacheMap + tagCache *tagCache + structCache *structCache errsPool *sync.Pool } @@ -220,11 +220,17 @@ type FieldError struct { // New creates a new Validate instance for use. func New(config *Config) *Validate { + tc := new(tagCache) + tc.m.Store(make(map[string]*cTag)) + + sc := new(structCache) + sc.m.Store(make(map[reflect.Type]*cStruct)) + v := &Validate{ tagName: config.TagName, fieldNameTag: config.FieldNameTag, - tagCache: &tagCacheMap{m: map[string]*cachedTag{}}, - structCache: &structCacheMap{m: map[reflect.Type]*cachedStruct{}}, + tagCache: tc, + structCache: sc, errsPool: &sync.Pool{New: func() interface{} { return ValidationErrors{} }}} @@ -332,10 +338,28 @@ func (v *Validate) RegisterAliasValidation(alias, tags string) { func (v *Validate) Field(field interface{}, tag string) error { v.initCheck() + if len(tag) == 0 || tag == skipValidationTag { + return nil + } + errs := v.errsPool.Get().(ValidationErrors) fieldVal := reflect.ValueOf(field) - v.traverseField(fieldVal, fieldVal, fieldVal, blank, blank, errs, false, tag, blank, blank, false, false, nil, nil) + ctag, ok := v.tagCache.Get(tag) + if !ok { + v.tagCache.lock.Lock() + defer v.tagCache.lock.Unlock() + + // could have been multiple trying to access, but once first is done this ensures tag + // isn't parsed again. + ctag, ok = v.tagCache.Get(tag) + if !ok { + ctag, _ = v.parseFieldTagsRecursive(tag, blank, blank, false) + v.tagCache.Set(tag, ctag) + } + } + + v.traverseField(fieldVal, fieldVal, fieldVal, blank, blank, errs, false, false, nil, nil, defaultCField, ctag) if len(errs) == 0 { v.errsPool.Put(errs) @@ -352,10 +376,28 @@ func (v *Validate) Field(field interface{}, tag string) error { func (v *Validate) FieldWithValue(val interface{}, field interface{}, tag string) error { v.initCheck() + if len(tag) == 0 || tag == skipValidationTag { + return nil + } + errs := v.errsPool.Get().(ValidationErrors) topVal := reflect.ValueOf(val) - v.traverseField(topVal, topVal, reflect.ValueOf(field), blank, blank, errs, false, tag, blank, blank, false, false, nil, nil) + ctag, ok := v.tagCache.Get(tag) + if !ok { + v.tagCache.lock.Lock() + defer v.tagCache.lock.Unlock() + + // could have been multiple trying to access, but once first is done this ensures tag + // isn't parsed again. + ctag, ok = v.tagCache.Get(tag) + if !ok { + ctag, _ = v.parseFieldTagsRecursive(tag, blank, blank, false) + v.tagCache.Set(tag, ctag) + } + } + + v.traverseField(topVal, topVal, reflect.ValueOf(field), blank, blank, errs, false, false, nil, nil, defaultCField, ctag) if len(errs) == 0 { v.errsPool.Put(errs) @@ -374,7 +416,7 @@ func (v *Validate) StructPartial(current interface{}, fields ...string) error { sv, _ := v.ExtractType(reflect.ValueOf(current)) name := sv.Type().Name() - m := map[string]*struct{}{} + m := map[string]struct{}{} if fields != nil { for _, k := range fields { @@ -390,19 +432,19 @@ func (v *Validate) StructPartial(current interface{}, fields ...string) error { if idx != -1 { for idx != -1 { key += s[:idx] - m[key] = emptyStructPtr + m[key] = struct{}{} idx2 := strings.Index(s, rightBracket) idx2++ key += s[idx:idx2] - m[key] = emptyStructPtr + m[key] = struct{}{} s = s[idx2:] idx = strings.Index(s, leftBracket) } } else { key += s - m[key] = emptyStructPtr + m[key] = struct{}{} } key += namespaceSeparator @@ -413,7 +455,7 @@ func (v *Validate) StructPartial(current interface{}, fields ...string) error { errs := v.errsPool.Get().(ValidationErrors) - v.tranverseStruct(sv, sv, sv, blank, blank, errs, true, len(m) != 0, false, m, false) + v.ensureValidStruct(sv, sv, sv, blank, blank, errs, true, len(m) != 0, false, m, false) if len(errs) == 0 { v.errsPool.Put(errs) @@ -432,15 +474,15 @@ func (v *Validate) StructExcept(current interface{}, fields ...string) error { sv, _ := v.ExtractType(reflect.ValueOf(current)) name := sv.Type().Name() - m := map[string]*struct{}{} + m := map[string]struct{}{} for _, key := range fields { - m[name+namespaceSeparator+key] = emptyStructPtr + m[name+namespaceSeparator+key] = struct{}{} } errs := v.errsPool.Get().(ValidationErrors) - v.tranverseStruct(sv, sv, sv, blank, blank, errs, true, len(m) != 0, true, m, false) + v.ensureValidStruct(sv, sv, sv, blank, blank, errs, true, len(m) != 0, true, m, false) if len(errs) == 0 { v.errsPool.Put(errs) @@ -459,7 +501,7 @@ func (v *Validate) Struct(current interface{}) error { errs := v.errsPool.Get().(ValidationErrors) sv := reflect.ValueOf(current) - v.tranverseStruct(sv, sv, sv, blank, blank, errs, true, false, false, nil, false) + v.ensureValidStruct(sv, sv, sv, blank, blank, errs, true, false, false, nil, false) if len(errs) == 0 { v.errsPool.Put(errs) @@ -469,8 +511,7 @@ func (v *Validate) Struct(current interface{}) error { return errs } -// tranverseStruct traverses a structs fields and then passes them to be validated by traverseField -func (v *Validate) tranverseStruct(topStruct reflect.Value, currentStruct reflect.Value, current reflect.Value, errPrefix string, nsPrefix string, errs ValidationErrors, useStructName bool, partial bool, exclude bool, includeExclude map[string]*struct{}, isStructOnly bool) { +func (v *Validate) ensureValidStruct(topStruct reflect.Value, currentStruct reflect.Value, current reflect.Value, errPrefix string, nsPrefix string, errs ValidationErrors, useStructName bool, partial bool, exclude bool, includeExclude map[string]struct{}, isStructOnly bool) { if current.Kind() == reflect.Ptr && !current.IsNil() { current = current.Elem() @@ -480,134 +521,85 @@ func (v *Validate) tranverseStruct(topStruct reflect.Value, currentStruct reflec panic("value passed for validation is not a struct") } - // var ok bool + v.tranverseStruct(topStruct, currentStruct, current, errPrefix, nsPrefix, errs, useStructName, partial, exclude, includeExclude, nil, nil) +} + +// tranverseStruct traverses a structs fields and then passes them to be validated by traverseField +func (v *Validate) tranverseStruct(topStruct reflect.Value, currentStruct reflect.Value, current reflect.Value, errPrefix string, nsPrefix string, errs ValidationErrors, useStructName bool, partial bool, exclude bool, includeExclude map[string]struct{}, cs *cStruct, ct *cTag) { + + var ok bool + first := len(nsPrefix) == 0 typ := current.Type() - sName := typ.Name() + cs, ok = v.structCache.Get(typ) + if !ok { + cs = v.extractStructCache(current, typ.Name()) + } if useStructName { - errPrefix += sName + namespaceSeparator + errPrefix += cs.Name + namespaceSeparator - if v.fieldNameTag != blank { - nsPrefix += sName + namespaceSeparator + if len(v.fieldNameTag) != 0 { + nsPrefix += cs.Name + namespaceSeparator } } // structonly tag present don't tranverseFields // but must still check and run below struct level validation // if present - if !isStructOnly { + if first || ct == nil || ct.typeof != typeStructOnly { - var fld reflect.StructField + for _, f := range cs.fields { - // is anonymous struct, cannot parse or cache as - // it has no name to index by - if sName == blank { + if partial { - var customName string - var ok bool - numFields := current.NumField() + _, ok = includeExclude[errPrefix+f.Name] - for i := 0; i < numFields; i++ { - - fld = typ.Field(i) - - if fld.PkgPath != blank && !fld.Anonymous { + if (ok && exclude) || (!ok && !exclude) { continue } - - if partial { - - _, ok = includeExclude[errPrefix+fld.Name] - - if (ok && exclude) || (!ok && !exclude) { - continue - } - } - - customName = fld.Name - - if v.fieldNameTag != blank { - - name := strings.SplitN(fld.Tag.Get(v.fieldNameTag), ",", 2)[0] - - // dash check is for json "-" means don't output in json - if name != blank && name != dash { - customName = name - } - } - - v.traverseField(topStruct, currentStruct, current.Field(i), errPrefix, nsPrefix, errs, true, fld.Tag.Get(v.tagName), fld.Name, customName, partial, exclude, includeExclude, nil) - } - } else { - s, ok := v.structCache.Get(typ) - if !ok { - s = v.parseStruct(current, sName) } - for i, f := range s.fields { - - if partial { - - _, ok = includeExclude[errPrefix+f.Name] - - if (ok && exclude) || (!ok && !exclude) { - continue - } - } - fld = typ.Field(i) - - v.traverseField(topStruct, currentStruct, current.Field(i), errPrefix, nsPrefix, errs, true, f.CachedTag.tag, fld.Name, f.AltName, partial, exclude, includeExclude, f.CachedTag) - } + v.traverseField(topStruct, currentStruct, current.Field(f.Idx), errPrefix, nsPrefix, errs, partial, exclude, includeExclude, cs, f, f.cTags) } } // check if any struct level validations, after all field validations already checked. - if v.hasStructLevelFuncs { - if fn, ok := v.structLevelFuncs[current.Type()]; ok { - fn(v, &StructLevel{v: v, TopStruct: topStruct, CurrentStruct: current, errPrefix: errPrefix, nsPrefix: nsPrefix, errs: errs}) - } + if cs.fn != nil { + cs.fn(v, &StructLevel{v: v, TopStruct: topStruct, CurrentStruct: current, errPrefix: errPrefix, nsPrefix: nsPrefix, errs: errs}) } } // traverseField validates any field, be it a struct or single field, ensures it's validity and passes it along to be validated via it's tag options -func (v *Validate) traverseField(topStruct reflect.Value, currentStruct reflect.Value, current reflect.Value, errPrefix string, nsPrefix string, errs ValidationErrors, isStructField bool, tag, name, customName string, partial bool, exclude bool, includeExclude map[string]*struct{}, cTag *cachedTag) { +func (v *Validate) traverseField(topStruct reflect.Value, currentStruct reflect.Value, current reflect.Value, errPrefix string, nsPrefix string, errs ValidationErrors, partial bool, exclude bool, includeExclude map[string]struct{}, cs *cStruct, cf *cField, ct *cTag) { - if tag == skipValidationTag { - return - } - - if cTag == nil { - var isCached bool - cTag, isCached = v.tagCache.Get(tag) - - if !isCached { - cTag = v.parseTags(tag, name) - } - } - - current, kind := v.ExtractType(current) + current, kind, nullable := v.extractTypeInternal(current, false) var typ reflect.Type switch kind { case reflect.Ptr, reflect.Interface, reflect.Invalid: - if cTag.isOmitEmpty { + + if ct == nil { return } - if tag != blank { + if ct.typeof == typeOmitEmpty { + return + } - ns := errPrefix + name + if ct.hasTag { + + ns := errPrefix + cf.Name if kind == reflect.Invalid { errs[ns] = &FieldError{ FieldNamespace: ns, - NameNamespace: nsPrefix + customName, - Name: customName, - Field: name, - Tag: cTag.tags[0].tag, - ActualTag: cTag.tags[0].tagVals[0][0], - Param: cTag.tags[0].tagVals[0][1], + NameNamespace: nsPrefix + cf.AltName, + Name: cf.AltName, + Field: cf.Name, + Tag: ct.aliasTag, + ActualTag: ct.tag, + Param: ct.param, Kind: kind, } return @@ -615,12 +607,12 @@ func (v *Validate) traverseField(topStruct reflect.Value, currentStruct reflect. errs[ns] = &FieldError{ FieldNamespace: ns, - NameNamespace: nsPrefix + customName, - Name: customName, - Field: name, - Tag: cTag.tags[0].tag, - ActualTag: cTag.tags[0].tagVals[0][0], - Param: cTag.tags[0].tagVals[0][1], + NameNamespace: nsPrefix + cf.AltName, + Name: cf.AltName, + Field: cf.Name, + Tag: ct.aliasTag, + ActualTag: ct.tag, + Param: ct.param, Value: current.Interface(), Kind: kind, Type: current.Type(), @@ -629,169 +621,162 @@ func (v *Validate) traverseField(topStruct reflect.Value, currentStruct reflect. return } - // if we get here tag length is zero and we can leave - if kind == reflect.Invalid { - return - } - case reflect.Struct: typ = current.Type() if typ != timeType { - if cTag.isNoStructLevel { + if ct != nil { + ct = ct.next + } + + if ct != nil && ct.typeof == typeNoStructLevel { return } - v.tranverseStruct(topStruct, current, current, errPrefix+name+namespaceSeparator, nsPrefix+customName+namespaceSeparator, errs, false, partial, exclude, includeExclude, cTag.isStructOnly) + v.tranverseStruct(topStruct, current, current, errPrefix+cf.Name+namespaceSeparator, nsPrefix+cf.AltName+namespaceSeparator, errs, false, partial, exclude, includeExclude, cs, ct) return } } - if tag == blank { + if !ct.hasTag { return } typ = current.Type() - var dive bool - var diveSubTag string +OUTER: + for { + if ct == nil { + return + } - for _, valTag := range cTag.tags { + switch ct.typeof { - if valTag.tagVals[0][0] == existsTag { + case typeExists: + ct = ct.next continue - } - if valTag.tagVals[0][0] == diveTag { - dive = true - diveSubTag = strings.TrimLeft(strings.SplitN(cTag.diveTag, diveTag, 2)[1], ",") - break - } - - if valTag.tagVals[0][0] == omitempty { + case typeOmitEmpty: - if !HasValue(v, topStruct, currentStruct, current, typ, kind, blank) { + if !nullable && !HasValue(v, topStruct, currentStruct, current, typ, kind, blank) { return } + + ct = ct.next continue - } - if v.validateField(topStruct, currentStruct, current, typ, kind, errPrefix, nsPrefix, errs, valTag, name, customName) { - return - } - } + case typeDive: - if dive { - // traverse slice or map here - // or panic ;) - switch kind { - case reflect.Slice, reflect.Array: - v.traverseSlice(topStruct, currentStruct, current, errPrefix, nsPrefix, errs, diveSubTag, name, customName, partial, exclude, includeExclude, nil) - case reflect.Map: - v.traverseMap(topStruct, currentStruct, current, errPrefix, nsPrefix, errs, diveSubTag, name, customName, partial, exclude, includeExclude, nil) - default: - // throw error, if not a slice or map then should not have gotten here - // bad dive tag - panic("dive error! can't dive on a non slice or map") - } - } -} + ct = ct.next -// traverseSlice traverses a Slice or Array's elements and passes them to traverseField for validation -func (v *Validate) traverseSlice(topStruct reflect.Value, currentStruct reflect.Value, current reflect.Value, errPrefix string, nsPrefix string, errs ValidationErrors, tag, name, customName string, partial bool, exclude bool, includeExclude map[string]*struct{}, cTag *cachedTag) { + // traverse slice or map here + // or panic ;) + switch kind { + case reflect.Slice, reflect.Array: - for i := 0; i < current.Len(); i++ { - v.traverseField(topStruct, currentStruct, current.Index(i), errPrefix, nsPrefix, errs, false, tag, fmt.Sprintf(arrayIndexFieldName, name, i), fmt.Sprintf(arrayIndexFieldName, customName, i), partial, exclude, includeExclude, cTag) - } -} + for i := 0; i < current.Len(); i++ { + v.traverseField(topStruct, currentStruct, current.Index(i), errPrefix, nsPrefix, errs, partial, exclude, includeExclude, cs, &cField{Name: fmt.Sprintf(arrayIndexFieldName, cf.Name, i), AltName: fmt.Sprintf(arrayIndexFieldName, cf.AltName, i)}, ct) + } -// traverseMap traverses a map's elements and passes them to traverseField for validation -func (v *Validate) traverseMap(topStruct reflect.Value, currentStruct reflect.Value, current reflect.Value, errPrefix string, nsPrefix string, errs ValidationErrors, tag, name, customName string, partial bool, exclude bool, includeExclude map[string]*struct{}, cTag *cachedTag) { + case reflect.Map: + for _, key := range current.MapKeys() { + v.traverseField(topStruct, currentStruct, current.MapIndex(key), errPrefix, nsPrefix, errs, partial, exclude, includeExclude, cs, &cField{Name: fmt.Sprintf(mapIndexFieldName, cf.Name, key.Interface()), AltName: fmt.Sprintf(mapIndexFieldName, cf.AltName, key.Interface())}, ct) + } - for _, key := range current.MapKeys() { - v.traverseField(topStruct, currentStruct, current.MapIndex(key), errPrefix, nsPrefix, errs, false, tag, fmt.Sprintf(mapIndexFieldName, name, key.Interface()), fmt.Sprintf(mapIndexFieldName, customName, key.Interface()), partial, exclude, includeExclude, cTag) - } -} + default: + // throw error, if not a slice or map then should not have gotten here + // bad dive tag + panic("dive error! can't dive on a non slice or map") + } -// validateField validates a field based on the provided tag's key and param values and returns true if there is an error or false if all ok -func (v *Validate) validateField(topStruct reflect.Value, currentStruct reflect.Value, current reflect.Value, currentType reflect.Type, currentKind reflect.Kind, errPrefix string, nsPrefix string, errs ValidationErrors, valTag *tagVals, name, customName string) bool { + return - var valFunc Func - var ok bool + case typeOr: - if valTag.isOrVal { + errTag := blank - errTag := blank + for { - for _, val := range valTag.tagVals { + if ct.fn(v, topStruct, currentStruct, current, typ, kind, ct.param) { - valFunc, ok = v.validationFuncs[val[0]] - if !ok { - panic(strings.TrimSpace(fmt.Sprintf(undefinedValidation, name))) - } + // drain rest of the 'or' values, then continue or leave + for { - if valFunc(v, topStruct, currentStruct, current, currentType, currentKind, val[1]) { - return false - } + ct = ct.next - errTag += orSeparator + val[0] - } + if ct == nil { + return + } - ns := errPrefix + name + if ct.typeof != typeOr { + continue OUTER + } + } + } - if valTag.isAlias { - errs[ns] = &FieldError{ - FieldNamespace: ns, - NameNamespace: nsPrefix + customName, - Name: customName, - Field: name, - Tag: valTag.tag, - ActualTag: errTag[1:], - Value: current.Interface(), - Type: currentType, - Kind: currentKind, - } - } else { - errs[errPrefix+name] = &FieldError{ - FieldNamespace: ns, - NameNamespace: nsPrefix + customName, - Name: customName, - Field: name, - Tag: errTag[1:], - ActualTag: errTag[1:], - Value: current.Interface(), - Type: currentType, - Kind: currentKind, + errTag += orSeparator + ct.tag + + if ct.next == nil { + // if we get here, no valid 'or' value and no more tags + + ns := errPrefix + cf.Name + + if ct.hasAlias { + errs[ns] = &FieldError{ + FieldNamespace: ns, + NameNamespace: nsPrefix + cf.AltName, + Name: cf.AltName, + Field: cf.Name, + Tag: ct.aliasTag, + ActualTag: ct.actualAliasTag, + Value: current.Interface(), + Type: typ, + Kind: kind, + } + } else { + errs[errPrefix+cf.Name] = &FieldError{ + FieldNamespace: ns, + NameNamespace: nsPrefix + cf.AltName, + Name: cf.AltName, + Field: cf.Name, + Tag: errTag[1:], + ActualTag: errTag[1:], + Value: current.Interface(), + Type: typ, + Kind: kind, + } + } + + return + } + + ct = ct.next } - } - return true - } + default: + if !ct.fn(v, topStruct, currentStruct, current, typ, kind, ct.param) { - valFunc, ok = v.validationFuncs[valTag.tagVals[0][0]] - if !ok { - panic(strings.TrimSpace(fmt.Sprintf(undefinedValidation, name))) - } + ns := errPrefix + cf.Name - if valFunc(v, topStruct, currentStruct, current, currentType, currentKind, valTag.tagVals[0][1]) { - return false - } + errs[ns] = &FieldError{ + FieldNamespace: ns, + NameNamespace: nsPrefix + cf.AltName, + Name: cf.AltName, + Field: cf.Name, + Tag: ct.aliasTag, + ActualTag: ct.tag, + Value: current.Interface(), + Param: ct.param, + Type: typ, + Kind: kind, + } - ns := errPrefix + name + return - errs[ns] = &FieldError{ - FieldNamespace: ns, - NameNamespace: nsPrefix + customName, - Name: customName, - Field: name, - Tag: valTag.tag, - ActualTag: valTag.tagVals[0][0], - Value: current.Interface(), - Param: valTag.tagVals[0][1], - Type: currentType, - Kind: currentKind, - } + } - return true + ct = ct.next + } + } } diff --git a/vendor/gopkg.in/mgo.v2/LICENSE b/vendor/gopkg.in/mgo.v2/LICENSE deleted file mode 100644 index 770c767..0000000 --- a/vendor/gopkg.in/mgo.v2/LICENSE +++ /dev/null @@ -1,25 +0,0 @@ -mgo - MongoDB driver for Go - -Copyright (c) 2010-2013 - Gustavo Niemeyer - -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - -1. Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. -2. Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/gopkg.in/mgo.v2/Makefile b/vendor/gopkg.in/mgo.v2/Makefile deleted file mode 100644 index d1027d4..0000000 --- a/vendor/gopkg.in/mgo.v2/Makefile +++ /dev/null @@ -1,5 +0,0 @@ -startdb: - @harness/setup.sh start - -stopdb: - @harness/setup.sh stop diff --git a/vendor/gopkg.in/mgo.v2/README.md b/vendor/gopkg.in/mgo.v2/README.md deleted file mode 100644 index f4e452c..0000000 --- a/vendor/gopkg.in/mgo.v2/README.md +++ /dev/null @@ -1,4 +0,0 @@ -The MongoDB driver for Go -------------------------- - -Please go to [http://labix.org/mgo](http://labix.org/mgo) for all project details. diff --git a/vendor/gopkg.in/mgo.v2/auth.go b/vendor/gopkg.in/mgo.v2/auth.go deleted file mode 100644 index dc26e52..0000000 --- a/vendor/gopkg.in/mgo.v2/auth.go +++ /dev/null @@ -1,467 +0,0 @@ -// mgo - MongoDB driver for Go -// -// Copyright (c) 2010-2012 - Gustavo Niemeyer -// -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this -// list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR -// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package mgo - -import ( - "crypto/md5" - "crypto/sha1" - "encoding/hex" - "errors" - "fmt" - "sync" - - "gopkg.in/mgo.v2/bson" - "gopkg.in/mgo.v2/internal/scram" -) - -type authCmd struct { - Authenticate int - - Nonce string - User string - Key string -} - -type startSaslCmd struct { - StartSASL int `bson:"startSasl"` -} - -type authResult struct { - ErrMsg string - Ok bool -} - -type getNonceCmd struct { - GetNonce int -} - -type getNonceResult struct { - Nonce string - Err string "$err" - Code int -} - -type logoutCmd struct { - Logout int -} - -type saslCmd struct { - Start int `bson:"saslStart,omitempty"` - Continue int `bson:"saslContinue,omitempty"` - ConversationId int `bson:"conversationId,omitempty"` - Mechanism string `bson:"mechanism,omitempty"` - Payload []byte -} - -type saslResult struct { - Ok bool `bson:"ok"` - NotOk bool `bson:"code"` // Server <= 2.3.2 returns ok=1 & code>0 on errors (WTF?) - Done bool - - ConversationId int `bson:"conversationId"` - Payload []byte - ErrMsg string -} - -type saslStepper interface { - Step(serverData []byte) (clientData []byte, done bool, err error) - Close() -} - -func (socket *mongoSocket) getNonce() (nonce string, err error) { - socket.Lock() - for socket.cachedNonce == "" && socket.dead == nil { - debugf("Socket %p to %s: waiting for nonce", socket, socket.addr) - socket.gotNonce.Wait() - } - if socket.cachedNonce == "mongos" { - socket.Unlock() - return "", errors.New("Can't authenticate with mongos; see http://j.mp/mongos-auth") - } - debugf("Socket %p to %s: got nonce", socket, socket.addr) - nonce, err = socket.cachedNonce, socket.dead - socket.cachedNonce = "" - socket.Unlock() - if err != nil { - nonce = "" - } - return -} - -func (socket *mongoSocket) resetNonce() { - debugf("Socket %p to %s: requesting a new nonce", socket, socket.addr) - op := &queryOp{} - op.query = &getNonceCmd{GetNonce: 1} - op.collection = "admin.$cmd" - op.limit = -1 - op.replyFunc = func(err error, reply *replyOp, docNum int, docData []byte) { - if err != nil { - socket.kill(errors.New("getNonce: "+err.Error()), true) - return - } - result := &getNonceResult{} - err = bson.Unmarshal(docData, &result) - if err != nil { - socket.kill(errors.New("Failed to unmarshal nonce: "+err.Error()), true) - return - } - debugf("Socket %p to %s: nonce unmarshalled: %#v", socket, socket.addr, result) - if result.Code == 13390 { - // mongos doesn't yet support auth (see http://j.mp/mongos-auth) - result.Nonce = "mongos" - } else if result.Nonce == "" { - var msg string - if result.Err != "" { - msg = fmt.Sprintf("Got an empty nonce: %s (%d)", result.Err, result.Code) - } else { - msg = "Got an empty nonce" - } - socket.kill(errors.New(msg), true) - return - } - socket.Lock() - if socket.cachedNonce != "" { - socket.Unlock() - panic("resetNonce: nonce already cached") - } - socket.cachedNonce = result.Nonce - socket.gotNonce.Signal() - socket.Unlock() - } - err := socket.Query(op) - if err != nil { - socket.kill(errors.New("resetNonce: "+err.Error()), true) - } -} - -func (socket *mongoSocket) Login(cred Credential) error { - socket.Lock() - if cred.Mechanism == "" && socket.serverInfo.MaxWireVersion >= 3 { - cred.Mechanism = "SCRAM-SHA-1" - } - for _, sockCred := range socket.creds { - if sockCred == cred { - debugf("Socket %p to %s: login: db=%q user=%q (already logged in)", socket, socket.addr, cred.Source, cred.Username) - socket.Unlock() - return nil - } - } - if socket.dropLogout(cred) { - debugf("Socket %p to %s: login: db=%q user=%q (cached)", socket, socket.addr, cred.Source, cred.Username) - socket.creds = append(socket.creds, cred) - socket.Unlock() - return nil - } - socket.Unlock() - - debugf("Socket %p to %s: login: db=%q user=%q", socket, socket.addr, cred.Source, cred.Username) - - var err error - switch cred.Mechanism { - case "", "MONGODB-CR", "MONGO-CR": // Name changed to MONGODB-CR in SERVER-8501. - err = socket.loginClassic(cred) - case "PLAIN": - err = socket.loginPlain(cred) - case "MONGODB-X509": - err = socket.loginX509(cred) - default: - // Try SASL for everything else, if it is available. - err = socket.loginSASL(cred) - } - - if err != nil { - debugf("Socket %p to %s: login error: %s", socket, socket.addr, err) - } else { - debugf("Socket %p to %s: login successful", socket, socket.addr) - } - return err -} - -func (socket *mongoSocket) loginClassic(cred Credential) error { - // Note that this only works properly because this function is - // synchronous, which means the nonce won't get reset while we're - // using it and any other login requests will block waiting for a - // new nonce provided in the defer call below. - nonce, err := socket.getNonce() - if err != nil { - return err - } - defer socket.resetNonce() - - psum := md5.New() - psum.Write([]byte(cred.Username + ":mongo:" + cred.Password)) - - ksum := md5.New() - ksum.Write([]byte(nonce + cred.Username)) - ksum.Write([]byte(hex.EncodeToString(psum.Sum(nil)))) - - key := hex.EncodeToString(ksum.Sum(nil)) - - cmd := authCmd{Authenticate: 1, User: cred.Username, Nonce: nonce, Key: key} - res := authResult{} - return socket.loginRun(cred.Source, &cmd, &res, func() error { - if !res.Ok { - return errors.New(res.ErrMsg) - } - socket.Lock() - socket.dropAuth(cred.Source) - socket.creds = append(socket.creds, cred) - socket.Unlock() - return nil - }) -} - -type authX509Cmd struct { - Authenticate int - User string - Mechanism string -} - -func (socket *mongoSocket) loginX509(cred Credential) error { - cmd := authX509Cmd{Authenticate: 1, User: cred.Username, Mechanism: "MONGODB-X509"} - res := authResult{} - return socket.loginRun(cred.Source, &cmd, &res, func() error { - if !res.Ok { - return errors.New(res.ErrMsg) - } - socket.Lock() - socket.dropAuth(cred.Source) - socket.creds = append(socket.creds, cred) - socket.Unlock() - return nil - }) -} - -func (socket *mongoSocket) loginPlain(cred Credential) error { - cmd := saslCmd{Start: 1, Mechanism: "PLAIN", Payload: []byte("\x00" + cred.Username + "\x00" + cred.Password)} - res := authResult{} - return socket.loginRun(cred.Source, &cmd, &res, func() error { - if !res.Ok { - return errors.New(res.ErrMsg) - } - socket.Lock() - socket.dropAuth(cred.Source) - socket.creds = append(socket.creds, cred) - socket.Unlock() - return nil - }) -} - -func (socket *mongoSocket) loginSASL(cred Credential) error { - var sasl saslStepper - var err error - if cred.Mechanism == "SCRAM-SHA-1" { - // SCRAM is handled without external libraries. - sasl = saslNewScram(cred) - } else if len(cred.ServiceHost) > 0 { - sasl, err = saslNew(cred, cred.ServiceHost) - } else { - sasl, err = saslNew(cred, socket.Server().Addr) - } - if err != nil { - return err - } - defer sasl.Close() - - // The goal of this logic is to carry a locked socket until the - // local SASL step confirms the auth is valid; the socket needs to be - // locked so that concurrent action doesn't leave the socket in an - // auth state that doesn't reflect the operations that took place. - // As a simple case, imagine inverting login=>logout to logout=>login. - // - // The logic below works because the lock func isn't called concurrently. - locked := false - lock := func(b bool) { - if locked != b { - locked = b - if b { - socket.Lock() - } else { - socket.Unlock() - } - } - } - - lock(true) - defer lock(false) - - start := 1 - cmd := saslCmd{} - res := saslResult{} - for { - payload, done, err := sasl.Step(res.Payload) - if err != nil { - return err - } - if done && res.Done { - socket.dropAuth(cred.Source) - socket.creds = append(socket.creds, cred) - break - } - lock(false) - - cmd = saslCmd{ - Start: start, - Continue: 1 - start, - ConversationId: res.ConversationId, - Mechanism: cred.Mechanism, - Payload: payload, - } - start = 0 - err = socket.loginRun(cred.Source, &cmd, &res, func() error { - // See the comment on lock for why this is necessary. - lock(true) - if !res.Ok || res.NotOk { - return fmt.Errorf("server returned error on SASL authentication step: %s", res.ErrMsg) - } - return nil - }) - if err != nil { - return err - } - if done && res.Done { - socket.dropAuth(cred.Source) - socket.creds = append(socket.creds, cred) - break - } - } - - return nil -} - -func saslNewScram(cred Credential) *saslScram { - credsum := md5.New() - credsum.Write([]byte(cred.Username + ":mongo:" + cred.Password)) - client := scram.NewClient(sha1.New, cred.Username, hex.EncodeToString(credsum.Sum(nil))) - return &saslScram{cred: cred, client: client} -} - -type saslScram struct { - cred Credential - client *scram.Client -} - -func (s *saslScram) Close() {} - -func (s *saslScram) Step(serverData []byte) (clientData []byte, done bool, err error) { - more := s.client.Step(serverData) - return s.client.Out(), !more, s.client.Err() -} - -func (socket *mongoSocket) loginRun(db string, query, result interface{}, f func() error) error { - var mutex sync.Mutex - var replyErr error - mutex.Lock() - - op := queryOp{} - op.query = query - op.collection = db + ".$cmd" - op.limit = -1 - op.replyFunc = func(err error, reply *replyOp, docNum int, docData []byte) { - defer mutex.Unlock() - - if err != nil { - replyErr = err - return - } - - err = bson.Unmarshal(docData, result) - if err != nil { - replyErr = err - } else { - // Must handle this within the read loop for the socket, so - // that concurrent login requests are properly ordered. - replyErr = f() - } - } - - err := socket.Query(&op) - if err != nil { - return err - } - mutex.Lock() // Wait. - return replyErr -} - -func (socket *mongoSocket) Logout(db string) { - socket.Lock() - cred, found := socket.dropAuth(db) - if found { - debugf("Socket %p to %s: logout: db=%q (flagged)", socket, socket.addr, db) - socket.logout = append(socket.logout, cred) - } - socket.Unlock() -} - -func (socket *mongoSocket) LogoutAll() { - socket.Lock() - if l := len(socket.creds); l > 0 { - debugf("Socket %p to %s: logout all (flagged %d)", socket, socket.addr, l) - socket.logout = append(socket.logout, socket.creds...) - socket.creds = socket.creds[0:0] - } - socket.Unlock() -} - -func (socket *mongoSocket) flushLogout() (ops []interface{}) { - socket.Lock() - if l := len(socket.logout); l > 0 { - debugf("Socket %p to %s: logout all (flushing %d)", socket, socket.addr, l) - for i := 0; i != l; i++ { - op := queryOp{} - op.query = &logoutCmd{1} - op.collection = socket.logout[i].Source + ".$cmd" - op.limit = -1 - ops = append(ops, &op) - } - socket.logout = socket.logout[0:0] - } - socket.Unlock() - return -} - -func (socket *mongoSocket) dropAuth(db string) (cred Credential, found bool) { - for i, sockCred := range socket.creds { - if sockCred.Source == db { - copy(socket.creds[i:], socket.creds[i+1:]) - socket.creds = socket.creds[:len(socket.creds)-1] - return sockCred, true - } - } - return cred, false -} - -func (socket *mongoSocket) dropLogout(cred Credential) (found bool) { - for i, sockCred := range socket.logout { - if sockCred == cred { - copy(socket.logout[i:], socket.logout[i+1:]) - socket.logout = socket.logout[:len(socket.logout)-1] - return true - } - } - return false -} diff --git a/vendor/gopkg.in/mgo.v2/bson/LICENSE b/vendor/gopkg.in/mgo.v2/bson/LICENSE deleted file mode 100644 index 8903260..0000000 --- a/vendor/gopkg.in/mgo.v2/bson/LICENSE +++ /dev/null @@ -1,25 +0,0 @@ -BSON library for Go - -Copyright (c) 2010-2012 - Gustavo Niemeyer - -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - -1. Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. -2. Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/gopkg.in/mgo.v2/bson/bson.go b/vendor/gopkg.in/mgo.v2/bson/bson.go deleted file mode 100644 index 7fb7f8c..0000000 --- a/vendor/gopkg.in/mgo.v2/bson/bson.go +++ /dev/null @@ -1,738 +0,0 @@ -// BSON library for Go -// -// Copyright (c) 2010-2012 - Gustavo Niemeyer -// -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this -// list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR -// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// Package bson is an implementation of the BSON specification for Go: -// -// http://bsonspec.org -// -// It was created as part of the mgo MongoDB driver for Go, but is standalone -// and may be used on its own without the driver. -package bson - -import ( - "bytes" - "crypto/md5" - "crypto/rand" - "encoding/binary" - "encoding/hex" - "encoding/json" - "errors" - "fmt" - "io" - "os" - "reflect" - "runtime" - "strings" - "sync" - "sync/atomic" - "time" -) - -// -------------------------------------------------------------------------- -// The public API. - -// A value implementing the bson.Getter interface will have its GetBSON -// method called when the given value has to be marshalled, and the result -// of this method will be marshaled in place of the actual object. -// -// If GetBSON returns return a non-nil error, the marshalling procedure -// will stop and error out with the provided value. -type Getter interface { - GetBSON() (interface{}, error) -} - -// A value implementing the bson.Setter interface will receive the BSON -// value via the SetBSON method during unmarshaling, and the object -// itself will not be changed as usual. -// -// If setting the value works, the method should return nil or alternatively -// bson.SetZero to set the respective field to its zero value (nil for -// pointer types). If SetBSON returns a value of type bson.TypeError, the -// BSON value will be omitted from a map or slice being decoded and the -// unmarshalling will continue. If it returns any other non-nil error, the -// unmarshalling procedure will stop and error out with the provided value. -// -// This interface is generally useful in pointer receivers, since the method -// will want to change the receiver. A type field that implements the Setter -// interface doesn't have to be a pointer, though. -// -// Unlike the usual behavior, unmarshalling onto a value that implements a -// Setter interface will NOT reset the value to its zero state. This allows -// the value to decide by itself how to be unmarshalled. -// -// For example: -// -// type MyString string -// -// func (s *MyString) SetBSON(raw bson.Raw) error { -// return raw.Unmarshal(s) -// } -// -type Setter interface { - SetBSON(raw Raw) error -} - -// SetZero may be returned from a SetBSON method to have the value set to -// its respective zero value. When used in pointer values, this will set the -// field to nil rather than to the pre-allocated value. -var SetZero = errors.New("set to zero") - -// M is a convenient alias for a map[string]interface{} map, useful for -// dealing with BSON in a native way. For instance: -// -// bson.M{"a": 1, "b": true} -// -// There's no special handling for this type in addition to what's done anyway -// for an equivalent map type. Elements in the map will be dumped in an -// undefined ordered. See also the bson.D type for an ordered alternative. -type M map[string]interface{} - -// D represents a BSON document containing ordered elements. For example: -// -// bson.D{{"a", 1}, {"b", true}} -// -// In some situations, such as when creating indexes for MongoDB, the order in -// which the elements are defined is important. If the order is not important, -// using a map is generally more comfortable. See bson.M and bson.RawD. -type D []DocElem - -// DocElem is an element of the bson.D document representation. -type DocElem struct { - Name string - Value interface{} -} - -// Map returns a map out of the ordered element name/value pairs in d. -func (d D) Map() (m M) { - m = make(M, len(d)) - for _, item := range d { - m[item.Name] = item.Value - } - return m -} - -// The Raw type represents raw unprocessed BSON documents and elements. -// Kind is the kind of element as defined per the BSON specification, and -// Data is the raw unprocessed data for the respective element. -// Using this type it is possible to unmarshal or marshal values partially. -// -// Relevant documentation: -// -// http://bsonspec.org/#/specification -// -type Raw struct { - Kind byte - Data []byte -} - -// RawD represents a BSON document containing raw unprocessed elements. -// This low-level representation may be useful when lazily processing -// documents of uncertain content, or when manipulating the raw content -// documents in general. -type RawD []RawDocElem - -// See the RawD type. -type RawDocElem struct { - Name string - Value Raw -} - -// ObjectId is a unique ID identifying a BSON value. It must be exactly 12 bytes -// long. MongoDB objects by default have such a property set in their "_id" -// property. -// -// http://www.mongodb.org/display/DOCS/Object+IDs -type ObjectId string - -// ObjectIdHex returns an ObjectId from the provided hex representation. -// Calling this function with an invalid hex representation will -// cause a runtime panic. See the IsObjectIdHex function. -func ObjectIdHex(s string) ObjectId { - d, err := hex.DecodeString(s) - if err != nil || len(d) != 12 { - panic(fmt.Sprintf("invalid input to ObjectIdHex: %q", s)) - } - return ObjectId(d) -} - -// IsObjectIdHex returns whether s is a valid hex representation of -// an ObjectId. See the ObjectIdHex function. -func IsObjectIdHex(s string) bool { - if len(s) != 24 { - return false - } - _, err := hex.DecodeString(s) - return err == nil -} - -// objectIdCounter is atomically incremented when generating a new ObjectId -// using NewObjectId() function. It's used as a counter part of an id. -var objectIdCounter uint32 = readRandomUint32() - -// readRandomUint32 returns a random objectIdCounter. -func readRandomUint32() uint32 { - var b [4]byte - _, err := io.ReadFull(rand.Reader, b[:]) - if err != nil { - panic(fmt.Errorf("cannot read random object id: %v", err)) - } - return uint32((uint32(b[0]) << 0) | (uint32(b[1]) << 8) | (uint32(b[2]) << 16) | (uint32(b[3]) << 24)) -} - -// machineId stores machine id generated once and used in subsequent calls -// to NewObjectId function. -var machineId = readMachineId() -var processId = os.Getpid() - -// readMachineId generates and returns a machine id. -// If this function fails to get the hostname it will cause a runtime error. -func readMachineId() []byte { - var sum [3]byte - id := sum[:] - hostname, err1 := os.Hostname() - if err1 != nil { - _, err2 := io.ReadFull(rand.Reader, id) - if err2 != nil { - panic(fmt.Errorf("cannot get hostname: %v; %v", err1, err2)) - } - return id - } - hw := md5.New() - hw.Write([]byte(hostname)) - copy(id, hw.Sum(nil)) - return id -} - -// NewObjectId returns a new unique ObjectId. -func NewObjectId() ObjectId { - var b [12]byte - // Timestamp, 4 bytes, big endian - binary.BigEndian.PutUint32(b[:], uint32(time.Now().Unix())) - // Machine, first 3 bytes of md5(hostname) - b[4] = machineId[0] - b[5] = machineId[1] - b[6] = machineId[2] - // Pid, 2 bytes, specs don't specify endianness, but we use big endian. - b[7] = byte(processId >> 8) - b[8] = byte(processId) - // Increment, 3 bytes, big endian - i := atomic.AddUint32(&objectIdCounter, 1) - b[9] = byte(i >> 16) - b[10] = byte(i >> 8) - b[11] = byte(i) - return ObjectId(b[:]) -} - -// NewObjectIdWithTime returns a dummy ObjectId with the timestamp part filled -// with the provided number of seconds from epoch UTC, and all other parts -// filled with zeroes. It's not safe to insert a document with an id generated -// by this method, it is useful only for queries to find documents with ids -// generated before or after the specified timestamp. -func NewObjectIdWithTime(t time.Time) ObjectId { - var b [12]byte - binary.BigEndian.PutUint32(b[:4], uint32(t.Unix())) - return ObjectId(string(b[:])) -} - -// String returns a hex string representation of the id. -// Example: ObjectIdHex("4d88e15b60f486e428412dc9"). -func (id ObjectId) String() string { - return fmt.Sprintf(`ObjectIdHex("%x")`, string(id)) -} - -// Hex returns a hex representation of the ObjectId. -func (id ObjectId) Hex() string { - return hex.EncodeToString([]byte(id)) -} - -// MarshalJSON turns a bson.ObjectId into a json.Marshaller. -func (id ObjectId) MarshalJSON() ([]byte, error) { - return []byte(fmt.Sprintf(`"%x"`, string(id))), nil -} - -var nullBytes = []byte("null") - -// UnmarshalJSON turns *bson.ObjectId into a json.Unmarshaller. -func (id *ObjectId) UnmarshalJSON(data []byte) error { - if len(data) > 0 && (data[0] == '{' || data[0] == 'O') { - var v struct { - Id json.RawMessage `json:"$oid"` - Func struct { - Id json.RawMessage - } `json:"$oidFunc"` - } - err := jdec(data, &v) - if err == nil { - if len(v.Id) > 0 { - data = []byte(v.Id) - } else { - data = []byte(v.Func.Id) - } - } - } - if len(data) == 2 && data[0] == '"' && data[1] == '"' || bytes.Equal(data, nullBytes) { - *id = "" - return nil - } - if len(data) != 26 || data[0] != '"' || data[25] != '"' { - return errors.New(fmt.Sprintf("invalid ObjectId in JSON: %s", string(data))) - } - var buf [12]byte - _, err := hex.Decode(buf[:], data[1:25]) - if err != nil { - return errors.New(fmt.Sprintf("invalid ObjectId in JSON: %s (%s)", string(data), err)) - } - *id = ObjectId(string(buf[:])) - return nil -} - -// MarshalText turns bson.ObjectId into an encoding.TextMarshaler. -func (id ObjectId) MarshalText() ([]byte, error) { - return []byte(fmt.Sprintf("%x", string(id))), nil -} - -// UnmarshalText turns *bson.ObjectId into an encoding.TextUnmarshaler. -func (id *ObjectId) UnmarshalText(data []byte) error { - if len(data) == 1 && data[0] == ' ' || len(data) == 0 { - *id = "" - return nil - } - if len(data) != 24 { - return fmt.Errorf("invalid ObjectId: %s", data) - } - var buf [12]byte - _, err := hex.Decode(buf[:], data[:]) - if err != nil { - return fmt.Errorf("invalid ObjectId: %s (%s)", data, err) - } - *id = ObjectId(string(buf[:])) - return nil -} - -// Valid returns true if id is valid. A valid id must contain exactly 12 bytes. -func (id ObjectId) Valid() bool { - return len(id) == 12 -} - -// byteSlice returns byte slice of id from start to end. -// Calling this function with an invalid id will cause a runtime panic. -func (id ObjectId) byteSlice(start, end int) []byte { - if len(id) != 12 { - panic(fmt.Sprintf("invalid ObjectId: %q", string(id))) - } - return []byte(string(id)[start:end]) -} - -// Time returns the timestamp part of the id. -// It's a runtime error to call this method with an invalid id. -func (id ObjectId) Time() time.Time { - // First 4 bytes of ObjectId is 32-bit big-endian seconds from epoch. - secs := int64(binary.BigEndian.Uint32(id.byteSlice(0, 4))) - return time.Unix(secs, 0) -} - -// Machine returns the 3-byte machine id part of the id. -// It's a runtime error to call this method with an invalid id. -func (id ObjectId) Machine() []byte { - return id.byteSlice(4, 7) -} - -// Pid returns the process id part of the id. -// It's a runtime error to call this method with an invalid id. -func (id ObjectId) Pid() uint16 { - return binary.BigEndian.Uint16(id.byteSlice(7, 9)) -} - -// Counter returns the incrementing value part of the id. -// It's a runtime error to call this method with an invalid id. -func (id ObjectId) Counter() int32 { - b := id.byteSlice(9, 12) - // Counter is stored as big-endian 3-byte value - return int32(uint32(b[0])<<16 | uint32(b[1])<<8 | uint32(b[2])) -} - -// The Symbol type is similar to a string and is used in languages with a -// distinct symbol type. -type Symbol string - -// Now returns the current time with millisecond precision. MongoDB stores -// timestamps with the same precision, so a Time returned from this method -// will not change after a roundtrip to the database. That's the only reason -// why this function exists. Using the time.Now function also works fine -// otherwise. -func Now() time.Time { - return time.Unix(0, time.Now().UnixNano()/1e6*1e6) -} - -// MongoTimestamp is a special internal type used by MongoDB that for some -// strange reason has its own datatype defined in BSON. -type MongoTimestamp int64 - -type orderKey int64 - -// MaxKey is a special value that compares higher than all other possible BSON -// values in a MongoDB database. -var MaxKey = orderKey(1<<63 - 1) - -// MinKey is a special value that compares lower than all other possible BSON -// values in a MongoDB database. -var MinKey = orderKey(-1 << 63) - -type undefined struct{} - -// Undefined represents the undefined BSON value. -var Undefined undefined - -// Binary is a representation for non-standard binary values. Any kind should -// work, but the following are known as of this writing: -// -// 0x00 - Generic. This is decoded as []byte(data), not Binary{0x00, data}. -// 0x01 - Function (!?) -// 0x02 - Obsolete generic. -// 0x03 - UUID -// 0x05 - MD5 -// 0x80 - User defined. -// -type Binary struct { - Kind byte - Data []byte -} - -// RegEx represents a regular expression. The Options field may contain -// individual characters defining the way in which the pattern should be -// applied, and must be sorted. Valid options as of this writing are 'i' for -// case insensitive matching, 'm' for multi-line matching, 'x' for verbose -// mode, 'l' to make \w, \W, and similar be locale-dependent, 's' for dot-all -// mode (a '.' matches everything), and 'u' to make \w, \W, and similar match -// unicode. The value of the Options parameter is not verified before being -// marshaled into the BSON format. -type RegEx struct { - Pattern string - Options string -} - -// JavaScript is a type that holds JavaScript code. If Scope is non-nil, it -// will be marshaled as a mapping from identifiers to values that may be -// used when evaluating the provided Code. -type JavaScript struct { - Code string - Scope interface{} -} - -// DBPointer refers to a document id in a namespace. -// -// This type is deprecated in the BSON specification and should not be used -// except for backwards compatibility with ancient applications. -type DBPointer struct { - Namespace string - Id ObjectId -} - -const initialBufferSize = 64 - -func handleErr(err *error) { - if r := recover(); r != nil { - if _, ok := r.(runtime.Error); ok { - panic(r) - } else if _, ok := r.(externalPanic); ok { - panic(r) - } else if s, ok := r.(string); ok { - *err = errors.New(s) - } else if e, ok := r.(error); ok { - *err = e - } else { - panic(r) - } - } -} - -// Marshal serializes the in value, which may be a map or a struct value. -// In the case of struct values, only exported fields will be serialized, -// and the order of serialized fields will match that of the struct itself. -// The lowercased field name is used as the key for each exported field, -// but this behavior may be changed using the respective field tag. -// The tag may also contain flags to tweak the marshalling behavior for -// the field. The tag formats accepted are: -// -// "[][,[,]]" -// -// `(...) bson:"[][,[,]]" (...)` -// -// The following flags are currently supported: -// -// omitempty Only include the field if it's not set to the zero -// value for the type or to empty slices or maps. -// -// minsize Marshal an int64 value as an int32, if that's feasible -// while preserving the numeric value. -// -// inline Inline the field, which must be a struct or a map, -// causing all of its fields or keys to be processed as if -// they were part of the outer struct. For maps, keys must -// not conflict with the bson keys of other struct fields. -// -// Some examples: -// -// type T struct { -// A bool -// B int "myb" -// C string "myc,omitempty" -// D string `bson:",omitempty" json:"jsonkey"` -// E int64 ",minsize" -// F int64 "myf,omitempty,minsize" -// } -// -func Marshal(in interface{}) (out []byte, err error) { - defer handleErr(&err) - e := &encoder{make([]byte, 0, initialBufferSize)} - e.addDoc(reflect.ValueOf(in)) - return e.out, nil -} - -// Unmarshal deserializes data from in into the out value. The out value -// must be a map, a pointer to a struct, or a pointer to a bson.D value. -// In the case of struct values, only exported fields will be deserialized. -// The lowercased field name is used as the key for each exported field, -// but this behavior may be changed using the respective field tag. -// The tag may also contain flags to tweak the marshalling behavior for -// the field. The tag formats accepted are: -// -// "[][,[,]]" -// -// `(...) bson:"[][,[,]]" (...)` -// -// The following flags are currently supported during unmarshal (see the -// Marshal method for other flags): -// -// inline Inline the field, which must be a struct or a map. -// Inlined structs are handled as if its fields were part -// of the outer struct. An inlined map causes keys that do -// not match any other struct field to be inserted in the -// map rather than being discarded as usual. -// -// The target field or element types of out may not necessarily match -// the BSON values of the provided data. The following conversions are -// made automatically: -// -// - Numeric types are converted if at least the integer part of the -// value would be preserved correctly -// - Bools are converted to numeric types as 1 or 0 -// - Numeric types are converted to bools as true if not 0 or false otherwise -// - Binary and string BSON data is converted to a string, array or byte slice -// -// If the value would not fit the type and cannot be converted, it's -// silently skipped. -// -// Pointer values are initialized when necessary. -func Unmarshal(in []byte, out interface{}) (err error) { - if raw, ok := out.(*Raw); ok { - raw.Kind = 3 - raw.Data = in - return nil - } - defer handleErr(&err) - v := reflect.ValueOf(out) - switch v.Kind() { - case reflect.Ptr: - fallthrough - case reflect.Map: - d := newDecoder(in) - d.readDocTo(v) - case reflect.Struct: - return errors.New("Unmarshal can't deal with struct values. Use a pointer.") - default: - return errors.New("Unmarshal needs a map or a pointer to a struct.") - } - return nil -} - -// Unmarshal deserializes raw into the out value. If the out value type -// is not compatible with raw, a *bson.TypeError is returned. -// -// See the Unmarshal function documentation for more details on the -// unmarshalling process. -func (raw Raw) Unmarshal(out interface{}) (err error) { - defer handleErr(&err) - v := reflect.ValueOf(out) - switch v.Kind() { - case reflect.Ptr: - v = v.Elem() - fallthrough - case reflect.Map: - d := newDecoder(raw.Data) - good := d.readElemTo(v, raw.Kind) - if !good { - return &TypeError{v.Type(), raw.Kind} - } - case reflect.Struct: - return errors.New("Raw Unmarshal can't deal with struct values. Use a pointer.") - default: - return errors.New("Raw Unmarshal needs a map or a valid pointer.") - } - return nil -} - -type TypeError struct { - Type reflect.Type - Kind byte -} - -func (e *TypeError) Error() string { - return fmt.Sprintf("BSON kind 0x%02x isn't compatible with type %s", e.Kind, e.Type.String()) -} - -// -------------------------------------------------------------------------- -// Maintain a mapping of keys to structure field indexes - -type structInfo struct { - FieldsMap map[string]fieldInfo - FieldsList []fieldInfo - InlineMap int - Zero reflect.Value -} - -type fieldInfo struct { - Key string - Num int - OmitEmpty bool - MinSize bool - Inline []int -} - -var structMap = make(map[reflect.Type]*structInfo) -var structMapMutex sync.RWMutex - -type externalPanic string - -func (e externalPanic) String() string { - return string(e) -} - -func getStructInfo(st reflect.Type) (*structInfo, error) { - structMapMutex.RLock() - sinfo, found := structMap[st] - structMapMutex.RUnlock() - if found { - return sinfo, nil - } - n := st.NumField() - fieldsMap := make(map[string]fieldInfo) - fieldsList := make([]fieldInfo, 0, n) - inlineMap := -1 - for i := 0; i != n; i++ { - field := st.Field(i) - if field.PkgPath != "" && !field.Anonymous { - continue // Private field - } - - info := fieldInfo{Num: i} - - tag := field.Tag.Get("bson") - if tag == "" && strings.Index(string(field.Tag), ":") < 0 { - tag = string(field.Tag) - } - if tag == "-" { - continue - } - - inline := false - fields := strings.Split(tag, ",") - if len(fields) > 1 { - for _, flag := range fields[1:] { - switch flag { - case "omitempty": - info.OmitEmpty = true - case "minsize": - info.MinSize = true - case "inline": - inline = true - default: - msg := fmt.Sprintf("Unsupported flag %q in tag %q of type %s", flag, tag, st) - panic(externalPanic(msg)) - } - } - tag = fields[0] - } - - if inline { - switch field.Type.Kind() { - case reflect.Map: - if inlineMap >= 0 { - return nil, errors.New("Multiple ,inline maps in struct " + st.String()) - } - if field.Type.Key() != reflect.TypeOf("") { - return nil, errors.New("Option ,inline needs a map with string keys in struct " + st.String()) - } - inlineMap = info.Num - case reflect.Struct: - sinfo, err := getStructInfo(field.Type) - if err != nil { - return nil, err - } - for _, finfo := range sinfo.FieldsList { - if _, found := fieldsMap[finfo.Key]; found { - msg := "Duplicated key '" + finfo.Key + "' in struct " + st.String() - return nil, errors.New(msg) - } - if finfo.Inline == nil { - finfo.Inline = []int{i, finfo.Num} - } else { - finfo.Inline = append([]int{i}, finfo.Inline...) - } - fieldsMap[finfo.Key] = finfo - fieldsList = append(fieldsList, finfo) - } - default: - panic("Option ,inline needs a struct value or map field") - } - continue - } - - if tag != "" { - info.Key = tag - } else { - info.Key = strings.ToLower(field.Name) - } - - if _, found = fieldsMap[info.Key]; found { - msg := "Duplicated key '" + info.Key + "' in struct " + st.String() - return nil, errors.New(msg) - } - - fieldsList = append(fieldsList, info) - fieldsMap[info.Key] = info - } - sinfo = &structInfo{ - fieldsMap, - fieldsList, - inlineMap, - reflect.New(st).Elem(), - } - structMapMutex.Lock() - structMap[st] = sinfo - structMapMutex.Unlock() - return sinfo, nil -} diff --git a/vendor/gopkg.in/mgo.v2/bson/decimal.go b/vendor/gopkg.in/mgo.v2/bson/decimal.go deleted file mode 100644 index 3d2f700..0000000 --- a/vendor/gopkg.in/mgo.v2/bson/decimal.go +++ /dev/null @@ -1,310 +0,0 @@ -// BSON library for Go -// -// Copyright (c) 2010-2012 - Gustavo Niemeyer -// -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this -// list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR -// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package bson - -import ( - "fmt" - "strconv" - "strings" -) - -// Decimal128 holds decimal128 BSON values. -type Decimal128 struct { - h, l uint64 -} - -func (d Decimal128) String() string { - var pos int // positive sign - var e int // exponent - var h, l uint64 // significand high/low - - if d.h>>63&1 == 0 { - pos = 1 - } - - switch d.h >> 58 & (1<<5 - 1) { - case 0x1F: - return "NaN" - case 0x1E: - return "-Inf"[pos:] - } - - l = d.l - if d.h>>61&3 == 3 { - // Bits: 1*sign 2*ignored 14*exponent 111*significand. - // Implicit 0b100 prefix in significand. - e = int(d.h>>47&(1<<14-1)) - 6176 - //h = 4<<47 | d.h&(1<<47-1) - // Spec says all of these values are out of range. - h, l = 0, 0 - } else { - // Bits: 1*sign 14*exponent 113*significand - e = int(d.h>>49&(1<<14-1)) - 6176 - h = d.h & (1<<49 - 1) - } - - // Would be handled by the logic below, but that's trivial and common. - if h == 0 && l == 0 && e == 0 { - return "-0"[pos:] - } - - var repr [48]byte // Loop 5 times over 9 digits plus dot, negative sign, and leading zero. - var last = len(repr) - var i = len(repr) - var dot = len(repr) + e - var rem uint32 -Loop: - for d9 := 0; d9 < 5; d9++ { - h, l, rem = divmod(h, l, 1e9) - for d1 := 0; d1 < 9; d1++ { - // Handle "-0.0", "0.00123400", "-1.00E-6", "1.050E+3", etc. - if i < len(repr) && (dot == i || l == 0 && h == 0 && rem > 0 && rem < 10 && (dot < i-6 || e > 0)) { - e += len(repr) - i - i-- - repr[i] = '.' - last = i - 1 - dot = len(repr) // Unmark. - } - c := '0' + byte(rem%10) - rem /= 10 - i-- - repr[i] = c - // Handle "0E+3", "1E+3", etc. - if l == 0 && h == 0 && rem == 0 && i == len(repr)-1 && (dot < i-5 || e > 0) { - last = i - break Loop - } - if c != '0' { - last = i - } - // Break early. Works without it, but why. - if dot > i && l == 0 && h == 0 && rem == 0 { - break Loop - } - } - } - repr[last-1] = '-' - last-- - - if e > 0 { - return string(repr[last+pos:]) + "E+" + strconv.Itoa(e) - } - if e < 0 { - return string(repr[last+pos:]) + "E" + strconv.Itoa(e) - } - return string(repr[last+pos:]) -} - -func divmod(h, l uint64, div uint32) (qh, ql uint64, rem uint32) { - div64 := uint64(div) - a := h >> 32 - aq := a / div64 - ar := a % div64 - b := ar<<32 + h&(1<<32-1) - bq := b / div64 - br := b % div64 - c := br<<32 + l>>32 - cq := c / div64 - cr := c % div64 - d := cr<<32 + l&(1<<32-1) - dq := d / div64 - dr := d % div64 - return (aq<<32 | bq), (cq<<32 | dq), uint32(dr) -} - -var dNaN = Decimal128{0x1F << 58, 0} -var dPosInf = Decimal128{0x1E << 58, 0} -var dNegInf = Decimal128{0x3E << 58, 0} - -func dErr(s string) (Decimal128, error) { - return dNaN, fmt.Errorf("cannot parse %q as a decimal128", s) -} - -func ParseDecimal128(s string) (Decimal128, error) { - orig := s - if s == "" { - return dErr(orig) - } - neg := s[0] == '-' - if neg || s[0] == '+' { - s = s[1:] - } - - if (len(s) == 3 || len(s) == 8) && (s[0] == 'N' || s[0] == 'n' || s[0] == 'I' || s[0] == 'i') { - if s == "NaN" || s == "nan" || strings.EqualFold(s, "nan") { - return dNaN, nil - } - if s == "Inf" || s == "inf" || strings.EqualFold(s, "inf") || strings.EqualFold(s, "infinity") { - if neg { - return dNegInf, nil - } - return dPosInf, nil - } - return dErr(orig) - } - - var h, l uint64 - var e int - - var add, ovr uint32 - var mul uint32 = 1 - var dot = -1 - var digits = 0 - var i = 0 - for i < len(s) { - c := s[i] - if mul == 1e9 { - h, l, ovr = muladd(h, l, mul, add) - mul, add = 1, 0 - if ovr > 0 || h&((1<<15-1)<<49) > 0 { - return dErr(orig) - } - } - if c >= '0' && c <= '9' { - i++ - if c > '0' || digits > 0 { - digits++ - } - if digits > 34 { - if c == '0' { - // Exact rounding. - e++ - continue - } - return dErr(orig) - } - mul *= 10 - add *= 10 - add += uint32(c - '0') - continue - } - if c == '.' { - i++ - if dot >= 0 || i == 1 && len(s) == 1 { - return dErr(orig) - } - if i == len(s) { - break - } - if s[i] < '0' || s[i] > '9' || e > 0 { - return dErr(orig) - } - dot = i - continue - } - break - } - if i == 0 { - return dErr(orig) - } - if mul > 1 { - h, l, ovr = muladd(h, l, mul, add) - if ovr > 0 || h&((1<<15-1)<<49) > 0 { - return dErr(orig) - } - } - if dot >= 0 { - e += dot - i - } - if i+1 < len(s) && (s[i] == 'E' || s[i] == 'e') { - i++ - eneg := s[i] == '-' - if eneg || s[i] == '+' { - i++ - if i == len(s) { - return dErr(orig) - } - } - n := 0 - for i < len(s) && n < 1e4 { - c := s[i] - i++ - if c < '0' || c > '9' { - return dErr(orig) - } - n *= 10 - n += int(c - '0') - } - if eneg { - n = -n - } - e += n - for e < -6176 { - // Subnormal. - var div uint32 = 1 - for div < 1e9 && e < -6176 { - div *= 10 - e++ - } - var rem uint32 - h, l, rem = divmod(h, l, div) - if rem > 0 { - return dErr(orig) - } - } - for e > 6111 { - // Clamped. - var mul uint32 = 1 - for mul < 1e9 && e > 6111 { - mul *= 10 - e-- - } - h, l, ovr = muladd(h, l, mul, 0) - if ovr > 0 || h&((1<<15-1)<<49) > 0 { - return dErr(orig) - } - } - if e < -6176 || e > 6111 { - return dErr(orig) - } - } - - if i < len(s) { - return dErr(orig) - } - - h |= uint64(e+6176) & uint64(1<<14-1) << 49 - if neg { - h |= 1 << 63 - } - return Decimal128{h, l}, nil -} - -func muladd(h, l uint64, mul uint32, add uint32) (resh, resl uint64, overflow uint32) { - mul64 := uint64(mul) - a := mul64 * (l & (1<<32 - 1)) - b := a>>32 + mul64*(l>>32) - c := b>>32 + mul64*(h&(1<<32-1)) - d := c>>32 + mul64*(h>>32) - - a = a&(1<<32-1) + uint64(add) - b = b&(1<<32-1) + a>>32 - c = c&(1<<32-1) + b>>32 - d = d&(1<<32-1) + c>>32 - - return (d<<32 | c&(1<<32-1)), (b<<32 | a&(1<<32-1)), uint32(d >> 32) -} diff --git a/vendor/gopkg.in/mgo.v2/bson/decode.go b/vendor/gopkg.in/mgo.v2/bson/decode.go deleted file mode 100644 index 7c2d841..0000000 --- a/vendor/gopkg.in/mgo.v2/bson/decode.go +++ /dev/null @@ -1,849 +0,0 @@ -// BSON library for Go -// -// Copyright (c) 2010-2012 - Gustavo Niemeyer -// -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this -// list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR -// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// gobson - BSON library for Go. - -package bson - -import ( - "fmt" - "math" - "net/url" - "reflect" - "strconv" - "sync" - "time" -) - -type decoder struct { - in []byte - i int - docType reflect.Type -} - -var typeM = reflect.TypeOf(M{}) - -func newDecoder(in []byte) *decoder { - return &decoder{in, 0, typeM} -} - -// -------------------------------------------------------------------------- -// Some helper functions. - -func corrupted() { - panic("Document is corrupted") -} - -func settableValueOf(i interface{}) reflect.Value { - v := reflect.ValueOf(i) - sv := reflect.New(v.Type()).Elem() - sv.Set(v) - return sv -} - -// -------------------------------------------------------------------------- -// Unmarshaling of documents. - -const ( - setterUnknown = iota - setterNone - setterType - setterAddr -) - -var setterStyles map[reflect.Type]int -var setterIface reflect.Type -var setterMutex sync.RWMutex - -func init() { - var iface Setter - setterIface = reflect.TypeOf(&iface).Elem() - setterStyles = make(map[reflect.Type]int) -} - -func setterStyle(outt reflect.Type) int { - setterMutex.RLock() - style := setterStyles[outt] - setterMutex.RUnlock() - if style == setterUnknown { - setterMutex.Lock() - defer setterMutex.Unlock() - if outt.Implements(setterIface) { - setterStyles[outt] = setterType - } else if reflect.PtrTo(outt).Implements(setterIface) { - setterStyles[outt] = setterAddr - } else { - setterStyles[outt] = setterNone - } - style = setterStyles[outt] - } - return style -} - -func getSetter(outt reflect.Type, out reflect.Value) Setter { - style := setterStyle(outt) - if style == setterNone { - return nil - } - if style == setterAddr { - if !out.CanAddr() { - return nil - } - out = out.Addr() - } else if outt.Kind() == reflect.Ptr && out.IsNil() { - out.Set(reflect.New(outt.Elem())) - } - return out.Interface().(Setter) -} - -func clearMap(m reflect.Value) { - var none reflect.Value - for _, k := range m.MapKeys() { - m.SetMapIndex(k, none) - } -} - -func (d *decoder) readDocTo(out reflect.Value) { - var elemType reflect.Type - outt := out.Type() - outk := outt.Kind() - - for { - if outk == reflect.Ptr && out.IsNil() { - out.Set(reflect.New(outt.Elem())) - } - if setter := getSetter(outt, out); setter != nil { - var raw Raw - d.readDocTo(reflect.ValueOf(&raw)) - err := setter.SetBSON(raw) - if _, ok := err.(*TypeError); err != nil && !ok { - panic(err) - } - return - } - if outk == reflect.Ptr { - out = out.Elem() - outt = out.Type() - outk = out.Kind() - continue - } - break - } - - var fieldsMap map[string]fieldInfo - var inlineMap reflect.Value - start := d.i - - origout := out - if outk == reflect.Interface { - if d.docType.Kind() == reflect.Map { - mv := reflect.MakeMap(d.docType) - out.Set(mv) - out = mv - } else { - dv := reflect.New(d.docType).Elem() - out.Set(dv) - out = dv - } - outt = out.Type() - outk = outt.Kind() - } - - docType := d.docType - keyType := typeString - convertKey := false - switch outk { - case reflect.Map: - keyType = outt.Key() - if keyType.Kind() != reflect.String { - panic("BSON map must have string keys. Got: " + outt.String()) - } - if keyType != typeString { - convertKey = true - } - elemType = outt.Elem() - if elemType == typeIface { - d.docType = outt - } - if out.IsNil() { - out.Set(reflect.MakeMap(out.Type())) - } else if out.Len() > 0 { - clearMap(out) - } - case reflect.Struct: - if outt != typeRaw { - sinfo, err := getStructInfo(out.Type()) - if err != nil { - panic(err) - } - fieldsMap = sinfo.FieldsMap - out.Set(sinfo.Zero) - if sinfo.InlineMap != -1 { - inlineMap = out.Field(sinfo.InlineMap) - if !inlineMap.IsNil() && inlineMap.Len() > 0 { - clearMap(inlineMap) - } - elemType = inlineMap.Type().Elem() - if elemType == typeIface { - d.docType = inlineMap.Type() - } - } - } - case reflect.Slice: - switch outt.Elem() { - case typeDocElem: - origout.Set(d.readDocElems(outt)) - return - case typeRawDocElem: - origout.Set(d.readRawDocElems(outt)) - return - } - fallthrough - default: - panic("Unsupported document type for unmarshalling: " + out.Type().String()) - } - - end := int(d.readInt32()) - end += d.i - 4 - if end <= d.i || end > len(d.in) || d.in[end-1] != '\x00' { - corrupted() - } - for d.in[d.i] != '\x00' { - kind := d.readByte() - name := d.readCStr() - if d.i >= end { - corrupted() - } - - switch outk { - case reflect.Map: - e := reflect.New(elemType).Elem() - if d.readElemTo(e, kind) { - k := reflect.ValueOf(name) - if convertKey { - k = k.Convert(keyType) - } - out.SetMapIndex(k, e) - } - case reflect.Struct: - if outt == typeRaw { - d.dropElem(kind) - } else { - if info, ok := fieldsMap[name]; ok { - if info.Inline == nil { - d.readElemTo(out.Field(info.Num), kind) - } else { - d.readElemTo(out.FieldByIndex(info.Inline), kind) - } - } else if inlineMap.IsValid() { - if inlineMap.IsNil() { - inlineMap.Set(reflect.MakeMap(inlineMap.Type())) - } - e := reflect.New(elemType).Elem() - if d.readElemTo(e, kind) { - inlineMap.SetMapIndex(reflect.ValueOf(name), e) - } - } else { - d.dropElem(kind) - } - } - case reflect.Slice: - } - - if d.i >= end { - corrupted() - } - } - d.i++ // '\x00' - if d.i != end { - corrupted() - } - d.docType = docType - - if outt == typeRaw { - out.Set(reflect.ValueOf(Raw{0x03, d.in[start:d.i]})) - } -} - -func (d *decoder) readArrayDocTo(out reflect.Value) { - end := int(d.readInt32()) - end += d.i - 4 - if end <= d.i || end > len(d.in) || d.in[end-1] != '\x00' { - corrupted() - } - i := 0 - l := out.Len() - for d.in[d.i] != '\x00' { - if i >= l { - panic("Length mismatch on array field") - } - kind := d.readByte() - for d.i < end && d.in[d.i] != '\x00' { - d.i++ - } - if d.i >= end { - corrupted() - } - d.i++ - d.readElemTo(out.Index(i), kind) - if d.i >= end { - corrupted() - } - i++ - } - if i != l { - panic("Length mismatch on array field") - } - d.i++ // '\x00' - if d.i != end { - corrupted() - } -} - -func (d *decoder) readSliceDoc(t reflect.Type) interface{} { - tmp := make([]reflect.Value, 0, 8) - elemType := t.Elem() - if elemType == typeRawDocElem { - d.dropElem(0x04) - return reflect.Zero(t).Interface() - } - - end := int(d.readInt32()) - end += d.i - 4 - if end <= d.i || end > len(d.in) || d.in[end-1] != '\x00' { - corrupted() - } - for d.in[d.i] != '\x00' { - kind := d.readByte() - for d.i < end && d.in[d.i] != '\x00' { - d.i++ - } - if d.i >= end { - corrupted() - } - d.i++ - e := reflect.New(elemType).Elem() - if d.readElemTo(e, kind) { - tmp = append(tmp, e) - } - if d.i >= end { - corrupted() - } - } - d.i++ // '\x00' - if d.i != end { - corrupted() - } - - n := len(tmp) - slice := reflect.MakeSlice(t, n, n) - for i := 0; i != n; i++ { - slice.Index(i).Set(tmp[i]) - } - return slice.Interface() -} - -var typeSlice = reflect.TypeOf([]interface{}{}) -var typeIface = typeSlice.Elem() - -func (d *decoder) readDocElems(typ reflect.Type) reflect.Value { - docType := d.docType - d.docType = typ - slice := make([]DocElem, 0, 8) - d.readDocWith(func(kind byte, name string) { - e := DocElem{Name: name} - v := reflect.ValueOf(&e.Value) - if d.readElemTo(v.Elem(), kind) { - slice = append(slice, e) - } - }) - slicev := reflect.New(typ).Elem() - slicev.Set(reflect.ValueOf(slice)) - d.docType = docType - return slicev -} - -func (d *decoder) readRawDocElems(typ reflect.Type) reflect.Value { - docType := d.docType - d.docType = typ - slice := make([]RawDocElem, 0, 8) - d.readDocWith(func(kind byte, name string) { - e := RawDocElem{Name: name} - v := reflect.ValueOf(&e.Value) - if d.readElemTo(v.Elem(), kind) { - slice = append(slice, e) - } - }) - slicev := reflect.New(typ).Elem() - slicev.Set(reflect.ValueOf(slice)) - d.docType = docType - return slicev -} - -func (d *decoder) readDocWith(f func(kind byte, name string)) { - end := int(d.readInt32()) - end += d.i - 4 - if end <= d.i || end > len(d.in) || d.in[end-1] != '\x00' { - corrupted() - } - for d.in[d.i] != '\x00' { - kind := d.readByte() - name := d.readCStr() - if d.i >= end { - corrupted() - } - f(kind, name) - if d.i >= end { - corrupted() - } - } - d.i++ // '\x00' - if d.i != end { - corrupted() - } -} - -// -------------------------------------------------------------------------- -// Unmarshaling of individual elements within a document. - -var blackHole = settableValueOf(struct{}{}) - -func (d *decoder) dropElem(kind byte) { - d.readElemTo(blackHole, kind) -} - -// Attempt to decode an element from the document and put it into out. -// If the types are not compatible, the returned ok value will be -// false and out will be unchanged. -func (d *decoder) readElemTo(out reflect.Value, kind byte) (good bool) { - - start := d.i - - if kind == 0x03 { - // Delegate unmarshaling of documents. - outt := out.Type() - outk := out.Kind() - switch outk { - case reflect.Interface, reflect.Ptr, reflect.Struct, reflect.Map: - d.readDocTo(out) - return true - } - if setterStyle(outt) != setterNone { - d.readDocTo(out) - return true - } - if outk == reflect.Slice { - switch outt.Elem() { - case typeDocElem: - out.Set(d.readDocElems(outt)) - case typeRawDocElem: - out.Set(d.readRawDocElems(outt)) - default: - d.readDocTo(blackHole) - } - return true - } - d.readDocTo(blackHole) - return true - } - - var in interface{} - - switch kind { - case 0x01: // Float64 - in = d.readFloat64() - case 0x02: // UTF-8 string - in = d.readStr() - case 0x03: // Document - panic("Can't happen. Handled above.") - case 0x04: // Array - outt := out.Type() - if setterStyle(outt) != setterNone { - // Skip the value so its data is handed to the setter below. - d.dropElem(kind) - break - } - for outt.Kind() == reflect.Ptr { - outt = outt.Elem() - } - switch outt.Kind() { - case reflect.Array: - d.readArrayDocTo(out) - return true - case reflect.Slice: - in = d.readSliceDoc(outt) - default: - in = d.readSliceDoc(typeSlice) - } - case 0x05: // Binary - b := d.readBinary() - if b.Kind == 0x00 || b.Kind == 0x02 { - in = b.Data - } else { - in = b - } - case 0x06: // Undefined (obsolete, but still seen in the wild) - in = Undefined - case 0x07: // ObjectId - in = ObjectId(d.readBytes(12)) - case 0x08: // Bool - in = d.readBool() - case 0x09: // Timestamp - // MongoDB handles timestamps as milliseconds. - i := d.readInt64() - if i == -62135596800000 { - in = time.Time{} // In UTC for convenience. - } else { - in = time.Unix(i/1e3, i%1e3*1e6) - } - case 0x0A: // Nil - in = nil - case 0x0B: // RegEx - in = d.readRegEx() - case 0x0C: - in = DBPointer{Namespace: d.readStr(), Id: ObjectId(d.readBytes(12))} - case 0x0D: // JavaScript without scope - in = JavaScript{Code: d.readStr()} - case 0x0E: // Symbol - in = Symbol(d.readStr()) - case 0x0F: // JavaScript with scope - d.i += 4 // Skip length - js := JavaScript{d.readStr(), make(M)} - d.readDocTo(reflect.ValueOf(js.Scope)) - in = js - case 0x10: // Int32 - in = int(d.readInt32()) - case 0x11: // Mongo-specific timestamp - in = MongoTimestamp(d.readInt64()) - case 0x12: // Int64 - in = d.readInt64() - case 0x13: // Decimal128 - in = Decimal128{ - l: uint64(d.readInt64()), - h: uint64(d.readInt64()), - } - case 0x7F: // Max key - in = MaxKey - case 0xFF: // Min key - in = MinKey - default: - panic(fmt.Sprintf("Unknown element kind (0x%02X)", kind)) - } - - outt := out.Type() - - if outt == typeRaw { - out.Set(reflect.ValueOf(Raw{kind, d.in[start:d.i]})) - return true - } - - if setter := getSetter(outt, out); setter != nil { - err := setter.SetBSON(Raw{kind, d.in[start:d.i]}) - if err == SetZero { - out.Set(reflect.Zero(outt)) - return true - } - if err == nil { - return true - } - if _, ok := err.(*TypeError); !ok { - panic(err) - } - return false - } - - if in == nil { - out.Set(reflect.Zero(outt)) - return true - } - - outk := outt.Kind() - - // Dereference and initialize pointer if necessary. - first := true - for outk == reflect.Ptr { - if !out.IsNil() { - out = out.Elem() - } else { - elem := reflect.New(outt.Elem()) - if first { - // Only set if value is compatible. - first = false - defer func(out, elem reflect.Value) { - if good { - out.Set(elem) - } - }(out, elem) - } else { - out.Set(elem) - } - out = elem - } - outt = out.Type() - outk = outt.Kind() - } - - inv := reflect.ValueOf(in) - if outt == inv.Type() { - out.Set(inv) - return true - } - - switch outk { - case reflect.Interface: - out.Set(inv) - return true - case reflect.String: - switch inv.Kind() { - case reflect.String: - out.SetString(inv.String()) - return true - case reflect.Slice: - if b, ok := in.([]byte); ok { - out.SetString(string(b)) - return true - } - case reflect.Int, reflect.Int64: - if outt == typeJSONNumber { - out.SetString(strconv.FormatInt(inv.Int(), 10)) - return true - } - case reflect.Float64: - if outt == typeJSONNumber { - out.SetString(strconv.FormatFloat(inv.Float(), 'f', -1, 64)) - return true - } - } - case reflect.Slice, reflect.Array: - // Remember, array (0x04) slices are built with the correct - // element type. If we are here, must be a cross BSON kind - // conversion (e.g. 0x05 unmarshalling on string). - if outt.Elem().Kind() != reflect.Uint8 { - break - } - switch inv.Kind() { - case reflect.String: - slice := []byte(inv.String()) - out.Set(reflect.ValueOf(slice)) - return true - case reflect.Slice: - switch outt.Kind() { - case reflect.Array: - reflect.Copy(out, inv) - case reflect.Slice: - out.SetBytes(inv.Bytes()) - } - return true - } - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - switch inv.Kind() { - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - out.SetInt(inv.Int()) - return true - case reflect.Float32, reflect.Float64: - out.SetInt(int64(inv.Float())) - return true - case reflect.Bool: - if inv.Bool() { - out.SetInt(1) - } else { - out.SetInt(0) - } - return true - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - panic("can't happen: no uint types in BSON (!?)") - } - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - switch inv.Kind() { - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - out.SetUint(uint64(inv.Int())) - return true - case reflect.Float32, reflect.Float64: - out.SetUint(uint64(inv.Float())) - return true - case reflect.Bool: - if inv.Bool() { - out.SetUint(1) - } else { - out.SetUint(0) - } - return true - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - panic("Can't happen. No uint types in BSON.") - } - case reflect.Float32, reflect.Float64: - switch inv.Kind() { - case reflect.Float32, reflect.Float64: - out.SetFloat(inv.Float()) - return true - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - out.SetFloat(float64(inv.Int())) - return true - case reflect.Bool: - if inv.Bool() { - out.SetFloat(1) - } else { - out.SetFloat(0) - } - return true - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - panic("Can't happen. No uint types in BSON?") - } - case reflect.Bool: - switch inv.Kind() { - case reflect.Bool: - out.SetBool(inv.Bool()) - return true - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - out.SetBool(inv.Int() != 0) - return true - case reflect.Float32, reflect.Float64: - out.SetBool(inv.Float() != 0) - return true - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - panic("Can't happen. No uint types in BSON?") - } - case reflect.Struct: - if outt == typeURL && inv.Kind() == reflect.String { - u, err := url.Parse(inv.String()) - if err != nil { - panic(err) - } - out.Set(reflect.ValueOf(u).Elem()) - return true - } - if outt == typeBinary { - if b, ok := in.([]byte); ok { - out.Set(reflect.ValueOf(Binary{Data: b})) - return true - } - } - } - - return false -} - -// -------------------------------------------------------------------------- -// Parsers of basic types. - -func (d *decoder) readRegEx() RegEx { - re := RegEx{} - re.Pattern = d.readCStr() - re.Options = d.readCStr() - return re -} - -func (d *decoder) readBinary() Binary { - l := d.readInt32() - b := Binary{} - b.Kind = d.readByte() - b.Data = d.readBytes(l) - if b.Kind == 0x02 && len(b.Data) >= 4 { - // Weird obsolete format with redundant length. - b.Data = b.Data[4:] - } - return b -} - -func (d *decoder) readStr() string { - l := d.readInt32() - b := d.readBytes(l - 1) - if d.readByte() != '\x00' { - corrupted() - } - return string(b) -} - -func (d *decoder) readCStr() string { - start := d.i - end := start - l := len(d.in) - for ; end != l; end++ { - if d.in[end] == '\x00' { - break - } - } - d.i = end + 1 - if d.i > l { - corrupted() - } - return string(d.in[start:end]) -} - -func (d *decoder) readBool() bool { - b := d.readByte() - if b == 0 { - return false - } - if b == 1 { - return true - } - panic(fmt.Sprintf("encoded boolean must be 1 or 0, found %d", b)) -} - -func (d *decoder) readFloat64() float64 { - return math.Float64frombits(uint64(d.readInt64())) -} - -func (d *decoder) readInt32() int32 { - b := d.readBytes(4) - return int32((uint32(b[0]) << 0) | - (uint32(b[1]) << 8) | - (uint32(b[2]) << 16) | - (uint32(b[3]) << 24)) -} - -func (d *decoder) readInt64() int64 { - b := d.readBytes(8) - return int64((uint64(b[0]) << 0) | - (uint64(b[1]) << 8) | - (uint64(b[2]) << 16) | - (uint64(b[3]) << 24) | - (uint64(b[4]) << 32) | - (uint64(b[5]) << 40) | - (uint64(b[6]) << 48) | - (uint64(b[7]) << 56)) -} - -func (d *decoder) readByte() byte { - i := d.i - d.i++ - if d.i > len(d.in) { - corrupted() - } - return d.in[i] -} - -func (d *decoder) readBytes(length int32) []byte { - if length < 0 { - corrupted() - } - start := d.i - d.i += int(length) - if d.i < start || d.i > len(d.in) { - corrupted() - } - return d.in[start : start+int(length)] -} diff --git a/vendor/gopkg.in/mgo.v2/bson/encode.go b/vendor/gopkg.in/mgo.v2/bson/encode.go deleted file mode 100644 index add39e8..0000000 --- a/vendor/gopkg.in/mgo.v2/bson/encode.go +++ /dev/null @@ -1,514 +0,0 @@ -// BSON library for Go -// -// Copyright (c) 2010-2012 - Gustavo Niemeyer -// -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this -// list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR -// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// gobson - BSON library for Go. - -package bson - -import ( - "encoding/json" - "fmt" - "math" - "net/url" - "reflect" - "strconv" - "time" -) - -// -------------------------------------------------------------------------- -// Some internal infrastructure. - -var ( - typeBinary = reflect.TypeOf(Binary{}) - typeObjectId = reflect.TypeOf(ObjectId("")) - typeDBPointer = reflect.TypeOf(DBPointer{"", ObjectId("")}) - typeSymbol = reflect.TypeOf(Symbol("")) - typeMongoTimestamp = reflect.TypeOf(MongoTimestamp(0)) - typeOrderKey = reflect.TypeOf(MinKey) - typeDocElem = reflect.TypeOf(DocElem{}) - typeRawDocElem = reflect.TypeOf(RawDocElem{}) - typeRaw = reflect.TypeOf(Raw{}) - typeURL = reflect.TypeOf(url.URL{}) - typeTime = reflect.TypeOf(time.Time{}) - typeString = reflect.TypeOf("") - typeJSONNumber = reflect.TypeOf(json.Number("")) -) - -const itoaCacheSize = 32 - -var itoaCache []string - -func init() { - itoaCache = make([]string, itoaCacheSize) - for i := 0; i != itoaCacheSize; i++ { - itoaCache[i] = strconv.Itoa(i) - } -} - -func itoa(i int) string { - if i < itoaCacheSize { - return itoaCache[i] - } - return strconv.Itoa(i) -} - -// -------------------------------------------------------------------------- -// Marshaling of the document value itself. - -type encoder struct { - out []byte -} - -func (e *encoder) addDoc(v reflect.Value) { - for { - if vi, ok := v.Interface().(Getter); ok { - getv, err := vi.GetBSON() - if err != nil { - panic(err) - } - v = reflect.ValueOf(getv) - continue - } - if v.Kind() == reflect.Ptr { - v = v.Elem() - continue - } - break - } - - if v.Type() == typeRaw { - raw := v.Interface().(Raw) - if raw.Kind != 0x03 && raw.Kind != 0x00 { - panic("Attempted to marshal Raw kind " + strconv.Itoa(int(raw.Kind)) + " as a document") - } - if len(raw.Data) == 0 { - panic("Attempted to marshal empty Raw document") - } - e.addBytes(raw.Data...) - return - } - - start := e.reserveInt32() - - switch v.Kind() { - case reflect.Map: - e.addMap(v) - case reflect.Struct: - e.addStruct(v) - case reflect.Array, reflect.Slice: - e.addSlice(v) - default: - panic("Can't marshal " + v.Type().String() + " as a BSON document") - } - - e.addBytes(0) - e.setInt32(start, int32(len(e.out)-start)) -} - -func (e *encoder) addMap(v reflect.Value) { - for _, k := range v.MapKeys() { - e.addElem(k.String(), v.MapIndex(k), false) - } -} - -func (e *encoder) addStruct(v reflect.Value) { - sinfo, err := getStructInfo(v.Type()) - if err != nil { - panic(err) - } - var value reflect.Value - if sinfo.InlineMap >= 0 { - m := v.Field(sinfo.InlineMap) - if m.Len() > 0 { - for _, k := range m.MapKeys() { - ks := k.String() - if _, found := sinfo.FieldsMap[ks]; found { - panic(fmt.Sprintf("Can't have key %q in inlined map; conflicts with struct field", ks)) - } - e.addElem(ks, m.MapIndex(k), false) - } - } - } - for _, info := range sinfo.FieldsList { - if info.Inline == nil { - value = v.Field(info.Num) - } else { - value = v.FieldByIndex(info.Inline) - } - if info.OmitEmpty && isZero(value) { - continue - } - e.addElem(info.Key, value, info.MinSize) - } -} - -func isZero(v reflect.Value) bool { - switch v.Kind() { - case reflect.String: - return len(v.String()) == 0 - case reflect.Ptr, reflect.Interface: - return v.IsNil() - case reflect.Slice: - return v.Len() == 0 - case reflect.Map: - return v.Len() == 0 - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return v.Int() == 0 - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - return v.Uint() == 0 - case reflect.Float32, reflect.Float64: - return v.Float() == 0 - case reflect.Bool: - return !v.Bool() - case reflect.Struct: - vt := v.Type() - if vt == typeTime { - return v.Interface().(time.Time).IsZero() - } - for i := 0; i < v.NumField(); i++ { - if vt.Field(i).PkgPath != "" && !vt.Field(i).Anonymous { - continue // Private field - } - if !isZero(v.Field(i)) { - return false - } - } - return true - } - return false -} - -func (e *encoder) addSlice(v reflect.Value) { - vi := v.Interface() - if d, ok := vi.(D); ok { - for _, elem := range d { - e.addElem(elem.Name, reflect.ValueOf(elem.Value), false) - } - return - } - if d, ok := vi.(RawD); ok { - for _, elem := range d { - e.addElem(elem.Name, reflect.ValueOf(elem.Value), false) - } - return - } - l := v.Len() - et := v.Type().Elem() - if et == typeDocElem { - for i := 0; i < l; i++ { - elem := v.Index(i).Interface().(DocElem) - e.addElem(elem.Name, reflect.ValueOf(elem.Value), false) - } - return - } - if et == typeRawDocElem { - for i := 0; i < l; i++ { - elem := v.Index(i).Interface().(RawDocElem) - e.addElem(elem.Name, reflect.ValueOf(elem.Value), false) - } - return - } - for i := 0; i < l; i++ { - e.addElem(itoa(i), v.Index(i), false) - } -} - -// -------------------------------------------------------------------------- -// Marshaling of elements in a document. - -func (e *encoder) addElemName(kind byte, name string) { - e.addBytes(kind) - e.addBytes([]byte(name)...) - e.addBytes(0) -} - -func (e *encoder) addElem(name string, v reflect.Value, minSize bool) { - - if !v.IsValid() { - e.addElemName(0x0A, name) - return - } - - if getter, ok := v.Interface().(Getter); ok { - getv, err := getter.GetBSON() - if err != nil { - panic(err) - } - e.addElem(name, reflect.ValueOf(getv), minSize) - return - } - - switch v.Kind() { - - case reflect.Interface: - e.addElem(name, v.Elem(), minSize) - - case reflect.Ptr: - e.addElem(name, v.Elem(), minSize) - - case reflect.String: - s := v.String() - switch v.Type() { - case typeObjectId: - if len(s) != 12 { - panic("ObjectIDs must be exactly 12 bytes long (got " + - strconv.Itoa(len(s)) + ")") - } - e.addElemName(0x07, name) - e.addBytes([]byte(s)...) - case typeSymbol: - e.addElemName(0x0E, name) - e.addStr(s) - case typeJSONNumber: - n := v.Interface().(json.Number) - if i, err := n.Int64(); err == nil { - e.addElemName(0x12, name) - e.addInt64(i) - } else if f, err := n.Float64(); err == nil { - e.addElemName(0x01, name) - e.addFloat64(f) - } else { - panic("failed to convert json.Number to a number: " + s) - } - default: - e.addElemName(0x02, name) - e.addStr(s) - } - - case reflect.Float32, reflect.Float64: - e.addElemName(0x01, name) - e.addFloat64(v.Float()) - - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - u := v.Uint() - if int64(u) < 0 { - panic("BSON has no uint64 type, and value is too large to fit correctly in an int64") - } else if u <= math.MaxInt32 && (minSize || v.Kind() <= reflect.Uint32) { - e.addElemName(0x10, name) - e.addInt32(int32(u)) - } else { - e.addElemName(0x12, name) - e.addInt64(int64(u)) - } - - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - switch v.Type() { - case typeMongoTimestamp: - e.addElemName(0x11, name) - e.addInt64(v.Int()) - - case typeOrderKey: - if v.Int() == int64(MaxKey) { - e.addElemName(0x7F, name) - } else { - e.addElemName(0xFF, name) - } - - default: - i := v.Int() - if (minSize || v.Type().Kind() != reflect.Int64) && i >= math.MinInt32 && i <= math.MaxInt32 { - // It fits into an int32, encode as such. - e.addElemName(0x10, name) - e.addInt32(int32(i)) - } else { - e.addElemName(0x12, name) - e.addInt64(i) - } - } - - case reflect.Bool: - e.addElemName(0x08, name) - if v.Bool() { - e.addBytes(1) - } else { - e.addBytes(0) - } - - case reflect.Map: - e.addElemName(0x03, name) - e.addDoc(v) - - case reflect.Slice: - vt := v.Type() - et := vt.Elem() - if et.Kind() == reflect.Uint8 { - e.addElemName(0x05, name) - e.addBinary(0x00, v.Bytes()) - } else if et == typeDocElem || et == typeRawDocElem { - e.addElemName(0x03, name) - e.addDoc(v) - } else { - e.addElemName(0x04, name) - e.addDoc(v) - } - - case reflect.Array: - et := v.Type().Elem() - if et.Kind() == reflect.Uint8 { - e.addElemName(0x05, name) - if v.CanAddr() { - e.addBinary(0x00, v.Slice(0, v.Len()).Interface().([]byte)) - } else { - n := v.Len() - e.addInt32(int32(n)) - e.addBytes(0x00) - for i := 0; i < n; i++ { - el := v.Index(i) - e.addBytes(byte(el.Uint())) - } - } - } else { - e.addElemName(0x04, name) - e.addDoc(v) - } - - case reflect.Struct: - switch s := v.Interface().(type) { - - case Raw: - kind := s.Kind - if kind == 0x00 { - kind = 0x03 - } - if len(s.Data) == 0 && kind != 0x06 && kind != 0x0A && kind != 0xFF && kind != 0x7F { - panic("Attempted to marshal empty Raw document") - } - e.addElemName(kind, name) - e.addBytes(s.Data...) - - case Binary: - e.addElemName(0x05, name) - e.addBinary(s.Kind, s.Data) - - case Decimal128: - e.addElemName(0x13, name) - e.addInt64(int64(s.l)) - e.addInt64(int64(s.h)) - - case DBPointer: - e.addElemName(0x0C, name) - e.addStr(s.Namespace) - if len(s.Id) != 12 { - panic("ObjectIDs must be exactly 12 bytes long (got " + - strconv.Itoa(len(s.Id)) + ")") - } - e.addBytes([]byte(s.Id)...) - - case RegEx: - e.addElemName(0x0B, name) - e.addCStr(s.Pattern) - e.addCStr(s.Options) - - case JavaScript: - if s.Scope == nil { - e.addElemName(0x0D, name) - e.addStr(s.Code) - } else { - e.addElemName(0x0F, name) - start := e.reserveInt32() - e.addStr(s.Code) - e.addDoc(reflect.ValueOf(s.Scope)) - e.setInt32(start, int32(len(e.out)-start)) - } - - case time.Time: - // MongoDB handles timestamps as milliseconds. - e.addElemName(0x09, name) - e.addInt64(s.Unix()*1000 + int64(s.Nanosecond()/1e6)) - - case url.URL: - e.addElemName(0x02, name) - e.addStr(s.String()) - - case undefined: - e.addElemName(0x06, name) - - default: - e.addElemName(0x03, name) - e.addDoc(v) - } - - default: - panic("Can't marshal " + v.Type().String() + " in a BSON document") - } -} - -// -------------------------------------------------------------------------- -// Marshaling of base types. - -func (e *encoder) addBinary(subtype byte, v []byte) { - if subtype == 0x02 { - // Wonder how that brilliant idea came to life. Obsolete, luckily. - e.addInt32(int32(len(v) + 4)) - e.addBytes(subtype) - e.addInt32(int32(len(v))) - } else { - e.addInt32(int32(len(v))) - e.addBytes(subtype) - } - e.addBytes(v...) -} - -func (e *encoder) addStr(v string) { - e.addInt32(int32(len(v) + 1)) - e.addCStr(v) -} - -func (e *encoder) addCStr(v string) { - e.addBytes([]byte(v)...) - e.addBytes(0) -} - -func (e *encoder) reserveInt32() (pos int) { - pos = len(e.out) - e.addBytes(0, 0, 0, 0) - return pos -} - -func (e *encoder) setInt32(pos int, v int32) { - e.out[pos+0] = byte(v) - e.out[pos+1] = byte(v >> 8) - e.out[pos+2] = byte(v >> 16) - e.out[pos+3] = byte(v >> 24) -} - -func (e *encoder) addInt32(v int32) { - u := uint32(v) - e.addBytes(byte(u), byte(u>>8), byte(u>>16), byte(u>>24)) -} - -func (e *encoder) addInt64(v int64) { - u := uint64(v) - e.addBytes(byte(u), byte(u>>8), byte(u>>16), byte(u>>24), - byte(u>>32), byte(u>>40), byte(u>>48), byte(u>>56)) -} - -func (e *encoder) addFloat64(v float64) { - e.addInt64(int64(math.Float64bits(v))) -} - -func (e *encoder) addBytes(v ...byte) { - e.out = append(e.out, v...) -} diff --git a/vendor/gopkg.in/mgo.v2/bson/json.go b/vendor/gopkg.in/mgo.v2/bson/json.go deleted file mode 100644 index 09df826..0000000 --- a/vendor/gopkg.in/mgo.v2/bson/json.go +++ /dev/null @@ -1,380 +0,0 @@ -package bson - -import ( - "bytes" - "encoding/base64" - "fmt" - "gopkg.in/mgo.v2/internal/json" - "strconv" - "time" -) - -// UnmarshalJSON unmarshals a JSON value that may hold non-standard -// syntax as defined in BSON's extended JSON specification. -func UnmarshalJSON(data []byte, value interface{}) error { - d := json.NewDecoder(bytes.NewBuffer(data)) - d.Extend(&jsonExt) - return d.Decode(value) -} - -// MarshalJSON marshals a JSON value that may hold non-standard -// syntax as defined in BSON's extended JSON specification. -func MarshalJSON(value interface{}) ([]byte, error) { - var buf bytes.Buffer - e := json.NewEncoder(&buf) - e.Extend(&jsonExt) - err := e.Encode(value) - if err != nil { - return nil, err - } - return buf.Bytes(), nil -} - -// jdec is used internally by the JSON decoding functions -// so they may unmarshal functions without getting into endless -// recursion due to keyed objects. -func jdec(data []byte, value interface{}) error { - d := json.NewDecoder(bytes.NewBuffer(data)) - d.Extend(&funcExt) - return d.Decode(value) -} - -var jsonExt json.Extension -var funcExt json.Extension - -// TODO -// - Shell regular expressions ("/regexp/opts") - -func init() { - jsonExt.DecodeUnquotedKeys(true) - jsonExt.DecodeTrailingCommas(true) - - funcExt.DecodeFunc("BinData", "$binaryFunc", "$type", "$binary") - jsonExt.DecodeKeyed("$binary", jdecBinary) - jsonExt.DecodeKeyed("$binaryFunc", jdecBinary) - jsonExt.EncodeType([]byte(nil), jencBinarySlice) - jsonExt.EncodeType(Binary{}, jencBinaryType) - - funcExt.DecodeFunc("ISODate", "$dateFunc", "S") - funcExt.DecodeFunc("new Date", "$dateFunc", "S") - jsonExt.DecodeKeyed("$date", jdecDate) - jsonExt.DecodeKeyed("$dateFunc", jdecDate) - jsonExt.EncodeType(time.Time{}, jencDate) - - funcExt.DecodeFunc("Timestamp", "$timestamp", "t", "i") - jsonExt.DecodeKeyed("$timestamp", jdecTimestamp) - jsonExt.EncodeType(MongoTimestamp(0), jencTimestamp) - - funcExt.DecodeConst("undefined", Undefined) - - jsonExt.DecodeKeyed("$regex", jdecRegEx) - jsonExt.EncodeType(RegEx{}, jencRegEx) - - funcExt.DecodeFunc("ObjectId", "$oidFunc", "Id") - jsonExt.DecodeKeyed("$oid", jdecObjectId) - jsonExt.DecodeKeyed("$oidFunc", jdecObjectId) - jsonExt.EncodeType(ObjectId(""), jencObjectId) - - funcExt.DecodeFunc("DBRef", "$dbrefFunc", "$ref", "$id") - jsonExt.DecodeKeyed("$dbrefFunc", jdecDBRef) - - funcExt.DecodeFunc("NumberLong", "$numberLongFunc", "N") - jsonExt.DecodeKeyed("$numberLong", jdecNumberLong) - jsonExt.DecodeKeyed("$numberLongFunc", jdecNumberLong) - jsonExt.EncodeType(int64(0), jencNumberLong) - jsonExt.EncodeType(int(0), jencInt) - - funcExt.DecodeConst("MinKey", MinKey) - funcExt.DecodeConst("MaxKey", MaxKey) - jsonExt.DecodeKeyed("$minKey", jdecMinKey) - jsonExt.DecodeKeyed("$maxKey", jdecMaxKey) - jsonExt.EncodeType(orderKey(0), jencMinMaxKey) - - jsonExt.DecodeKeyed("$undefined", jdecUndefined) - jsonExt.EncodeType(Undefined, jencUndefined) - - jsonExt.Extend(&funcExt) -} - -func fbytes(format string, args ...interface{}) []byte { - var buf bytes.Buffer - fmt.Fprintf(&buf, format, args...) - return buf.Bytes() -} - -func jdecBinary(data []byte) (interface{}, error) { - var v struct { - Binary []byte `json:"$binary"` - Type string `json:"$type"` - Func struct { - Binary []byte `json:"$binary"` - Type int64 `json:"$type"` - } `json:"$binaryFunc"` - } - err := jdec(data, &v) - if err != nil { - return nil, err - } - - var binData []byte - var binKind int64 - if v.Type == "" && v.Binary == nil { - binData = v.Func.Binary - binKind = v.Func.Type - } else if v.Type == "" { - return v.Binary, nil - } else { - binData = v.Binary - binKind, err = strconv.ParseInt(v.Type, 0, 64) - if err != nil { - binKind = -1 - } - } - - if binKind == 0 { - return binData, nil - } - if binKind < 0 || binKind > 255 { - return nil, fmt.Errorf("invalid type in binary object: %s", data) - } - - return Binary{Kind: byte(binKind), Data: binData}, nil -} - -func jencBinarySlice(v interface{}) ([]byte, error) { - in := v.([]byte) - out := make([]byte, base64.StdEncoding.EncodedLen(len(in))) - base64.StdEncoding.Encode(out, in) - return fbytes(`{"$binary":"%s","$type":"0x0"}`, out), nil -} - -func jencBinaryType(v interface{}) ([]byte, error) { - in := v.(Binary) - out := make([]byte, base64.StdEncoding.EncodedLen(len(in.Data))) - base64.StdEncoding.Encode(out, in.Data) - return fbytes(`{"$binary":"%s","$type":"0x%x"}`, out, in.Kind), nil -} - -const jdateFormat = "2006-01-02T15:04:05.999Z" - -func jdecDate(data []byte) (interface{}, error) { - var v struct { - S string `json:"$date"` - Func struct { - S string - } `json:"$dateFunc"` - } - _ = jdec(data, &v) - if v.S == "" { - v.S = v.Func.S - } - if v.S != "" { - for _, format := range []string{jdateFormat, "2006-01-02"} { - t, err := time.Parse(format, v.S) - if err == nil { - return t, nil - } - } - return nil, fmt.Errorf("cannot parse date: %q", v.S) - } - - var vn struct { - Date struct { - N int64 `json:"$numberLong,string"` - } `json:"$date"` - Func struct { - S int64 - } `json:"$dateFunc"` - } - err := jdec(data, &vn) - if err != nil { - return nil, fmt.Errorf("cannot parse date: %q", data) - } - n := vn.Date.N - if n == 0 { - n = vn.Func.S - } - return time.Unix(n/1000, n%1000*1e6).UTC(), nil -} - -func jencDate(v interface{}) ([]byte, error) { - t := v.(time.Time) - return fbytes(`{"$date":%q}`, t.Format(jdateFormat)), nil -} - -func jdecTimestamp(data []byte) (interface{}, error) { - var v struct { - Func struct { - T int32 `json:"t"` - I int32 `json:"i"` - } `json:"$timestamp"` - } - err := jdec(data, &v) - if err != nil { - return nil, err - } - return MongoTimestamp(uint64(v.Func.T)<<32 | uint64(uint32(v.Func.I))), nil -} - -func jencTimestamp(v interface{}) ([]byte, error) { - ts := uint64(v.(MongoTimestamp)) - return fbytes(`{"$timestamp":{"t":%d,"i":%d}}`, ts>>32, uint32(ts)), nil -} - -func jdecRegEx(data []byte) (interface{}, error) { - var v struct { - Regex string `json:"$regex"` - Options string `json:"$options"` - } - err := jdec(data, &v) - if err != nil { - return nil, err - } - return RegEx{v.Regex, v.Options}, nil -} - -func jencRegEx(v interface{}) ([]byte, error) { - re := v.(RegEx) - type regex struct { - Regex string `json:"$regex"` - Options string `json:"$options"` - } - return json.Marshal(regex{re.Pattern, re.Options}) -} - -func jdecObjectId(data []byte) (interface{}, error) { - var v struct { - Id string `json:"$oid"` - Func struct { - Id string - } `json:"$oidFunc"` - } - err := jdec(data, &v) - if err != nil { - return nil, err - } - if v.Id == "" { - v.Id = v.Func.Id - } - return ObjectIdHex(v.Id), nil -} - -func jencObjectId(v interface{}) ([]byte, error) { - return fbytes(`{"$oid":"%s"}`, v.(ObjectId).Hex()), nil -} - -func jdecDBRef(data []byte) (interface{}, error) { - // TODO Support unmarshaling $ref and $id into the input value. - var v struct { - Obj map[string]interface{} `json:"$dbrefFunc"` - } - // TODO Fix this. Must not be required. - v.Obj = make(map[string]interface{}) - err := jdec(data, &v) - if err != nil { - return nil, err - } - return v.Obj, nil -} - -func jdecNumberLong(data []byte) (interface{}, error) { - var v struct { - N int64 `json:"$numberLong,string"` - Func struct { - N int64 `json:",string"` - } `json:"$numberLongFunc"` - } - var vn struct { - N int64 `json:"$numberLong"` - Func struct { - N int64 - } `json:"$numberLongFunc"` - } - err := jdec(data, &v) - if err != nil { - err = jdec(data, &vn) - v.N = vn.N - v.Func.N = vn.Func.N - } - if err != nil { - return nil, err - } - if v.N != 0 { - return v.N, nil - } - return v.Func.N, nil -} - -func jencNumberLong(v interface{}) ([]byte, error) { - n := v.(int64) - f := `{"$numberLong":"%d"}` - if n <= 1<<53 { - f = `{"$numberLong":%d}` - } - return fbytes(f, n), nil -} - -func jencInt(v interface{}) ([]byte, error) { - n := v.(int) - f := `{"$numberLong":"%d"}` - if int64(n) <= 1<<53 { - f = `%d` - } - return fbytes(f, n), nil -} - -func jdecMinKey(data []byte) (interface{}, error) { - var v struct { - N int64 `json:"$minKey"` - } - err := jdec(data, &v) - if err != nil { - return nil, err - } - if v.N != 1 { - return nil, fmt.Errorf("invalid $minKey object: %s", data) - } - return MinKey, nil -} - -func jdecMaxKey(data []byte) (interface{}, error) { - var v struct { - N int64 `json:"$maxKey"` - } - err := jdec(data, &v) - if err != nil { - return nil, err - } - if v.N != 1 { - return nil, fmt.Errorf("invalid $maxKey object: %s", data) - } - return MaxKey, nil -} - -func jencMinMaxKey(v interface{}) ([]byte, error) { - switch v.(orderKey) { - case MinKey: - return []byte(`{"$minKey":1}`), nil - case MaxKey: - return []byte(`{"$maxKey":1}`), nil - } - panic(fmt.Sprintf("invalid $minKey/$maxKey value: %d", v)) -} - -func jdecUndefined(data []byte) (interface{}, error) { - var v struct { - B bool `json:"$undefined"` - } - err := jdec(data, &v) - if err != nil { - return nil, err - } - if !v.B { - return nil, fmt.Errorf("invalid $undefined object: %s", data) - } - return Undefined, nil -} - -func jencUndefined(v interface{}) ([]byte, error) { - return []byte(`{"$undefined":true}`), nil -} diff --git a/vendor/gopkg.in/mgo.v2/bulk.go b/vendor/gopkg.in/mgo.v2/bulk.go deleted file mode 100644 index 072a520..0000000 --- a/vendor/gopkg.in/mgo.v2/bulk.go +++ /dev/null @@ -1,351 +0,0 @@ -package mgo - -import ( - "bytes" - "sort" - - "gopkg.in/mgo.v2/bson" -) - -// Bulk represents an operation that can be prepared with several -// orthogonal changes before being delivered to the server. -// -// MongoDB servers older than version 2.6 do not have proper support for bulk -// operations, so the driver attempts to map its API as much as possible into -// the functionality that works. In particular, in those releases updates and -// removals are sent individually, and inserts are sent in bulk but have -// suboptimal error reporting compared to more recent versions of the server. -// See the documentation of BulkErrorCase for details on that. -// -// Relevant documentation: -// -// http://blog.mongodb.org/post/84922794768/mongodbs-new-bulk-api -// -type Bulk struct { - c *Collection - opcount int - actions []bulkAction - ordered bool -} - -type bulkOp int - -const ( - bulkInsert bulkOp = iota + 1 - bulkUpdate - bulkUpdateAll - bulkRemove -) - -type bulkAction struct { - op bulkOp - docs []interface{} - idxs []int -} - -type bulkUpdateOp []interface{} -type bulkDeleteOp []interface{} - -// BulkResult holds the results for a bulk operation. -type BulkResult struct { - Matched int - Modified int // Available only for MongoDB 2.6+ - - // Be conservative while we understand exactly how to report these - // results in a useful and convenient way, and also how to emulate - // them with prior servers. - private bool -} - -// BulkError holds an error returned from running a Bulk operation. -// Individual errors may be obtained and inspected via the Cases method. -type BulkError struct { - ecases []BulkErrorCase -} - -func (e *BulkError) Error() string { - if len(e.ecases) == 0 { - return "invalid BulkError instance: no errors" - } - if len(e.ecases) == 1 { - return e.ecases[0].Err.Error() - } - msgs := make([]string, 0, len(e.ecases)) - seen := make(map[string]bool) - for _, ecase := range e.ecases { - msg := ecase.Err.Error() - if !seen[msg] { - seen[msg] = true - msgs = append(msgs, msg) - } - } - if len(msgs) == 1 { - return msgs[0] - } - var buf bytes.Buffer - buf.WriteString("multiple errors in bulk operation:\n") - for _, msg := range msgs { - buf.WriteString(" - ") - buf.WriteString(msg) - buf.WriteByte('\n') - } - return buf.String() -} - -type bulkErrorCases []BulkErrorCase - -func (slice bulkErrorCases) Len() int { return len(slice) } -func (slice bulkErrorCases) Less(i, j int) bool { return slice[i].Index < slice[j].Index } -func (slice bulkErrorCases) Swap(i, j int) { slice[i], slice[j] = slice[j], slice[i] } - -// BulkErrorCase holds an individual error found while attempting a single change -// within a bulk operation, and the position in which it was enqueued. -// -// MongoDB servers older than version 2.6 do not have proper support for bulk -// operations, so the driver attempts to map its API as much as possible into -// the functionality that works. In particular, only the last error is reported -// for bulk inserts and without any positional information, so the Index -// field is set to -1 in these cases. -type BulkErrorCase struct { - Index int // Position of operation that failed, or -1 if unknown. - Err error -} - -// Cases returns all individual errors found while attempting the requested changes. -// -// See the documentation of BulkErrorCase for limitations in older MongoDB releases. -func (e *BulkError) Cases() []BulkErrorCase { - return e.ecases -} - -// Bulk returns a value to prepare the execution of a bulk operation. -func (c *Collection) Bulk() *Bulk { - return &Bulk{c: c, ordered: true} -} - -// Unordered puts the bulk operation in unordered mode. -// -// In unordered mode the indvidual operations may be sent -// out of order, which means latter operations may proceed -// even if prior ones have failed. -func (b *Bulk) Unordered() { - b.ordered = false -} - -func (b *Bulk) action(op bulkOp, opcount int) *bulkAction { - var action *bulkAction - if len(b.actions) > 0 && b.actions[len(b.actions)-1].op == op { - action = &b.actions[len(b.actions)-1] - } else if !b.ordered { - for i := range b.actions { - if b.actions[i].op == op { - action = &b.actions[i] - break - } - } - } - if action == nil { - b.actions = append(b.actions, bulkAction{op: op}) - action = &b.actions[len(b.actions)-1] - } - for i := 0; i < opcount; i++ { - action.idxs = append(action.idxs, b.opcount) - b.opcount++ - } - return action -} - -// Insert queues up the provided documents for insertion. -func (b *Bulk) Insert(docs ...interface{}) { - action := b.action(bulkInsert, len(docs)) - action.docs = append(action.docs, docs...) -} - -// Remove queues up the provided selectors for removing matching documents. -// Each selector will remove only a single matching document. -func (b *Bulk) Remove(selectors ...interface{}) { - action := b.action(bulkRemove, len(selectors)) - for _, selector := range selectors { - if selector == nil { - selector = bson.D{} - } - action.docs = append(action.docs, &deleteOp{ - Collection: b.c.FullName, - Selector: selector, - Flags: 1, - Limit: 1, - }) - } -} - -// RemoveAll queues up the provided selectors for removing all matching documents. -// Each selector will remove all matching documents. -func (b *Bulk) RemoveAll(selectors ...interface{}) { - action := b.action(bulkRemove, len(selectors)) - for _, selector := range selectors { - if selector == nil { - selector = bson.D{} - } - action.docs = append(action.docs, &deleteOp{ - Collection: b.c.FullName, - Selector: selector, - Flags: 0, - Limit: 0, - }) - } -} - -// Update queues up the provided pairs of updating instructions. -// The first element of each pair selects which documents must be -// updated, and the second element defines how to update it. -// Each pair matches exactly one document for updating at most. -func (b *Bulk) Update(pairs ...interface{}) { - if len(pairs)%2 != 0 { - panic("Bulk.Update requires an even number of parameters") - } - action := b.action(bulkUpdate, len(pairs)/2) - for i := 0; i < len(pairs); i += 2 { - selector := pairs[i] - if selector == nil { - selector = bson.D{} - } - action.docs = append(action.docs, &updateOp{ - Collection: b.c.FullName, - Selector: selector, - Update: pairs[i+1], - }) - } -} - -// UpdateAll queues up the provided pairs of updating instructions. -// The first element of each pair selects which documents must be -// updated, and the second element defines how to update it. -// Each pair updates all documents matching the selector. -func (b *Bulk) UpdateAll(pairs ...interface{}) { - if len(pairs)%2 != 0 { - panic("Bulk.UpdateAll requires an even number of parameters") - } - action := b.action(bulkUpdate, len(pairs)/2) - for i := 0; i < len(pairs); i += 2 { - selector := pairs[i] - if selector == nil { - selector = bson.D{} - } - action.docs = append(action.docs, &updateOp{ - Collection: b.c.FullName, - Selector: selector, - Update: pairs[i+1], - Flags: 2, - Multi: true, - }) - } -} - -// Upsert queues up the provided pairs of upserting instructions. -// The first element of each pair selects which documents must be -// updated, and the second element defines how to update it. -// Each pair matches exactly one document for updating at most. -func (b *Bulk) Upsert(pairs ...interface{}) { - if len(pairs)%2 != 0 { - panic("Bulk.Update requires an even number of parameters") - } - action := b.action(bulkUpdate, len(pairs)/2) - for i := 0; i < len(pairs); i += 2 { - selector := pairs[i] - if selector == nil { - selector = bson.D{} - } - action.docs = append(action.docs, &updateOp{ - Collection: b.c.FullName, - Selector: selector, - Update: pairs[i+1], - Flags: 1, - Upsert: true, - }) - } -} - -// Run runs all the operations queued up. -// -// If an error is reported on an unordered bulk operation, the error value may -// be an aggregation of all issues observed. As an exception to that, Insert -// operations running on MongoDB versions prior to 2.6 will report the last -// error only due to a limitation in the wire protocol. -func (b *Bulk) Run() (*BulkResult, error) { - var result BulkResult - var berr BulkError - var failed bool - for i := range b.actions { - action := &b.actions[i] - var ok bool - switch action.op { - case bulkInsert: - ok = b.runInsert(action, &result, &berr) - case bulkUpdate: - ok = b.runUpdate(action, &result, &berr) - case bulkRemove: - ok = b.runRemove(action, &result, &berr) - default: - panic("unknown bulk operation") - } - if !ok { - failed = true - if b.ordered { - break - } - } - } - if failed { - sort.Sort(bulkErrorCases(berr.ecases)) - return nil, &berr - } - return &result, nil -} - -func (b *Bulk) runInsert(action *bulkAction, result *BulkResult, berr *BulkError) bool { - op := &insertOp{b.c.FullName, action.docs, 0} - if !b.ordered { - op.flags = 1 // ContinueOnError - } - lerr, err := b.c.writeOp(op, b.ordered) - return b.checkSuccess(action, berr, lerr, err) -} - -func (b *Bulk) runUpdate(action *bulkAction, result *BulkResult, berr *BulkError) bool { - lerr, err := b.c.writeOp(bulkUpdateOp(action.docs), b.ordered) - if lerr != nil { - result.Matched += lerr.N - result.Modified += lerr.modified - } - return b.checkSuccess(action, berr, lerr, err) -} - -func (b *Bulk) runRemove(action *bulkAction, result *BulkResult, berr *BulkError) bool { - lerr, err := b.c.writeOp(bulkDeleteOp(action.docs), b.ordered) - if lerr != nil { - result.Matched += lerr.N - result.Modified += lerr.modified - } - return b.checkSuccess(action, berr, lerr, err) -} - -func (b *Bulk) checkSuccess(action *bulkAction, berr *BulkError, lerr *LastError, err error) bool { - if lerr != nil && len(lerr.ecases) > 0 { - for i := 0; i < len(lerr.ecases); i++ { - // Map back from the local error index into the visible one. - ecase := lerr.ecases[i] - idx := ecase.Index - if idx >= 0 { - idx = action.idxs[idx] - } - berr.ecases = append(berr.ecases, BulkErrorCase{idx, ecase.Err}) - } - return false - } else if err != nil { - for i := 0; i < len(action.idxs); i++ { - berr.ecases = append(berr.ecases, BulkErrorCase{action.idxs[i], err}) - } - return false - } - return true -} diff --git a/vendor/gopkg.in/mgo.v2/cluster.go b/vendor/gopkg.in/mgo.v2/cluster.go deleted file mode 100644 index c3bf8b0..0000000 --- a/vendor/gopkg.in/mgo.v2/cluster.go +++ /dev/null @@ -1,682 +0,0 @@ -// mgo - MongoDB driver for Go -// -// Copyright (c) 2010-2012 - Gustavo Niemeyer -// -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this -// list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR -// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package mgo - -import ( - "errors" - "fmt" - "net" - "strconv" - "strings" - "sync" - "time" - - "gopkg.in/mgo.v2/bson" -) - -// --------------------------------------------------------------------------- -// Mongo cluster encapsulation. -// -// A cluster enables the communication with one or more servers participating -// in a mongo cluster. This works with individual servers, a replica set, -// a replica pair, one or multiple mongos routers, etc. - -type mongoCluster struct { - sync.RWMutex - serverSynced sync.Cond - userSeeds []string - dynaSeeds []string - servers mongoServers - masters mongoServers - references int - syncing bool - direct bool - failFast bool - syncCount uint - setName string - cachedIndex map[string]bool - sync chan bool - dial dialer -} - -func newCluster(userSeeds []string, direct, failFast bool, dial dialer, setName string) *mongoCluster { - cluster := &mongoCluster{ - userSeeds: userSeeds, - references: 1, - direct: direct, - failFast: failFast, - dial: dial, - setName: setName, - } - cluster.serverSynced.L = cluster.RWMutex.RLocker() - cluster.sync = make(chan bool, 1) - stats.cluster(+1) - go cluster.syncServersLoop() - return cluster -} - -// Acquire increases the reference count for the cluster. -func (cluster *mongoCluster) Acquire() { - cluster.Lock() - cluster.references++ - debugf("Cluster %p acquired (refs=%d)", cluster, cluster.references) - cluster.Unlock() -} - -// Release decreases the reference count for the cluster. Once -// it reaches zero, all servers will be closed. -func (cluster *mongoCluster) Release() { - cluster.Lock() - if cluster.references == 0 { - panic("cluster.Release() with references == 0") - } - cluster.references-- - debugf("Cluster %p released (refs=%d)", cluster, cluster.references) - if cluster.references == 0 { - for _, server := range cluster.servers.Slice() { - server.Close() - } - // Wake up the sync loop so it can die. - cluster.syncServers() - stats.cluster(-1) - } - cluster.Unlock() -} - -func (cluster *mongoCluster) LiveServers() (servers []string) { - cluster.RLock() - for _, serv := range cluster.servers.Slice() { - servers = append(servers, serv.Addr) - } - cluster.RUnlock() - return servers -} - -func (cluster *mongoCluster) removeServer(server *mongoServer) { - cluster.Lock() - cluster.masters.Remove(server) - other := cluster.servers.Remove(server) - cluster.Unlock() - if other != nil { - other.Close() - log("Removed server ", server.Addr, " from cluster.") - } - server.Close() -} - -type isMasterResult struct { - IsMaster bool - Secondary bool - Primary string - Hosts []string - Passives []string - Tags bson.D - Msg string - SetName string `bson:"setName"` - MaxWireVersion int `bson:"maxWireVersion"` -} - -func (cluster *mongoCluster) isMaster(socket *mongoSocket, result *isMasterResult) error { - // Monotonic let's it talk to a slave and still hold the socket. - session := newSession(Monotonic, cluster, 10*time.Second) - session.setSocket(socket) - err := session.Run("ismaster", result) - session.Close() - return err -} - -type possibleTimeout interface { - Timeout() bool -} - -var syncSocketTimeout = 5 * time.Second - -func (cluster *mongoCluster) syncServer(server *mongoServer) (info *mongoServerInfo, hosts []string, err error) { - var syncTimeout time.Duration - if raceDetector { - // This variable is only ever touched by tests. - globalMutex.Lock() - syncTimeout = syncSocketTimeout - globalMutex.Unlock() - } else { - syncTimeout = syncSocketTimeout - } - - addr := server.Addr - log("SYNC Processing ", addr, "...") - - // Retry a few times to avoid knocking a server down for a hiccup. - var result isMasterResult - var tryerr error - for retry := 0; ; retry++ { - if retry == 3 || retry == 1 && cluster.failFast { - return nil, nil, tryerr - } - if retry > 0 { - // Don't abuse the server needlessly if there's something actually wrong. - if err, ok := tryerr.(possibleTimeout); ok && err.Timeout() { - // Give a chance for waiters to timeout as well. - cluster.serverSynced.Broadcast() - } - time.Sleep(syncShortDelay) - } - - // It's not clear what would be a good timeout here. Is it - // better to wait longer or to retry? - socket, _, err := server.AcquireSocket(0, syncTimeout) - if err != nil { - tryerr = err - logf("SYNC Failed to get socket to %s: %v", addr, err) - continue - } - err = cluster.isMaster(socket, &result) - socket.Release() - if err != nil { - tryerr = err - logf("SYNC Command 'ismaster' to %s failed: %v", addr, err) - continue - } - debugf("SYNC Result of 'ismaster' from %s: %#v", addr, result) - break - } - - if cluster.setName != "" && result.SetName != cluster.setName { - logf("SYNC Server %s is not a member of replica set %q", addr, cluster.setName) - return nil, nil, fmt.Errorf("server %s is not a member of replica set %q", addr, cluster.setName) - } - - if result.IsMaster { - debugf("SYNC %s is a master.", addr) - if !server.info.Master { - // Made an incorrect assumption above, so fix stats. - stats.conn(-1, false) - stats.conn(+1, true) - } - } else if result.Secondary { - debugf("SYNC %s is a slave.", addr) - } else if cluster.direct { - logf("SYNC %s in unknown state. Pretending it's a slave due to direct connection.", addr) - } else { - logf("SYNC %s is neither a master nor a slave.", addr) - // Let stats track it as whatever was known before. - return nil, nil, errors.New(addr + " is not a master nor slave") - } - - info = &mongoServerInfo{ - Master: result.IsMaster, - Mongos: result.Msg == "isdbgrid", - Tags: result.Tags, - SetName: result.SetName, - MaxWireVersion: result.MaxWireVersion, - } - - hosts = make([]string, 0, 1+len(result.Hosts)+len(result.Passives)) - if result.Primary != "" { - // First in the list to speed up master discovery. - hosts = append(hosts, result.Primary) - } - hosts = append(hosts, result.Hosts...) - hosts = append(hosts, result.Passives...) - - debugf("SYNC %s knows about the following peers: %#v", addr, hosts) - return info, hosts, nil -} - -type syncKind bool - -const ( - completeSync syncKind = true - partialSync syncKind = false -) - -func (cluster *mongoCluster) addServer(server *mongoServer, info *mongoServerInfo, syncKind syncKind) { - cluster.Lock() - current := cluster.servers.Search(server.ResolvedAddr) - if current == nil { - if syncKind == partialSync { - cluster.Unlock() - server.Close() - log("SYNC Discarding unknown server ", server.Addr, " due to partial sync.") - return - } - cluster.servers.Add(server) - if info.Master { - cluster.masters.Add(server) - log("SYNC Adding ", server.Addr, " to cluster as a master.") - } else { - log("SYNC Adding ", server.Addr, " to cluster as a slave.") - } - } else { - if server != current { - panic("addServer attempting to add duplicated server") - } - if server.Info().Master != info.Master { - if info.Master { - log("SYNC Server ", server.Addr, " is now a master.") - cluster.masters.Add(server) - } else { - log("SYNC Server ", server.Addr, " is now a slave.") - cluster.masters.Remove(server) - } - } - } - server.SetInfo(info) - debugf("SYNC Broadcasting availability of server %s", server.Addr) - cluster.serverSynced.Broadcast() - cluster.Unlock() -} - -func (cluster *mongoCluster) getKnownAddrs() []string { - cluster.RLock() - max := len(cluster.userSeeds) + len(cluster.dynaSeeds) + cluster.servers.Len() - seen := make(map[string]bool, max) - known := make([]string, 0, max) - - add := func(addr string) { - if _, found := seen[addr]; !found { - seen[addr] = true - known = append(known, addr) - } - } - - for _, addr := range cluster.userSeeds { - add(addr) - } - for _, addr := range cluster.dynaSeeds { - add(addr) - } - for _, serv := range cluster.servers.Slice() { - add(serv.Addr) - } - cluster.RUnlock() - - return known -} - -// syncServers injects a value into the cluster.sync channel to force -// an iteration of the syncServersLoop function. -func (cluster *mongoCluster) syncServers() { - select { - case cluster.sync <- true: - default: - } -} - -// How long to wait for a checkup of the cluster topology if nothing -// else kicks a synchronization before that. -const syncServersDelay = 30 * time.Second -const syncShortDelay = 500 * time.Millisecond - -// syncServersLoop loops while the cluster is alive to keep its idea of -// the server topology up-to-date. It must be called just once from -// newCluster. The loop iterates once syncServersDelay has passed, or -// if somebody injects a value into the cluster.sync channel to force a -// synchronization. A loop iteration will contact all servers in -// parallel, ask them about known peers and their own role within the -// cluster, and then attempt to do the same with all the peers -// retrieved. -func (cluster *mongoCluster) syncServersLoop() { - for { - debugf("SYNC Cluster %p is starting a sync loop iteration.", cluster) - - cluster.Lock() - if cluster.references == 0 { - cluster.Unlock() - break - } - cluster.references++ // Keep alive while syncing. - direct := cluster.direct - cluster.Unlock() - - cluster.syncServersIteration(direct) - - // We just synchronized, so consume any outstanding requests. - select { - case <-cluster.sync: - default: - } - - cluster.Release() - - // Hold off before allowing another sync. No point in - // burning CPU looking for down servers. - if !cluster.failFast { - time.Sleep(syncShortDelay) - } - - cluster.Lock() - if cluster.references == 0 { - cluster.Unlock() - break - } - cluster.syncCount++ - // Poke all waiters so they have a chance to timeout or - // restart syncing if they wish to. - cluster.serverSynced.Broadcast() - // Check if we have to restart immediately either way. - restart := !direct && cluster.masters.Empty() || cluster.servers.Empty() - cluster.Unlock() - - if restart { - log("SYNC No masters found. Will synchronize again.") - time.Sleep(syncShortDelay) - continue - } - - debugf("SYNC Cluster %p waiting for next requested or scheduled sync.", cluster) - - // Hold off until somebody explicitly requests a synchronization - // or it's time to check for a cluster topology change again. - select { - case <-cluster.sync: - case <-time.After(syncServersDelay): - } - } - debugf("SYNC Cluster %p is stopping its sync loop.", cluster) -} - -func (cluster *mongoCluster) server(addr string, tcpaddr *net.TCPAddr) *mongoServer { - cluster.RLock() - server := cluster.servers.Search(tcpaddr.String()) - cluster.RUnlock() - if server != nil { - return server - } - return newServer(addr, tcpaddr, cluster.sync, cluster.dial) -} - -func resolveAddr(addr string) (*net.TCPAddr, error) { - // Simple cases that do not need actual resolution. Works with IPv4 and v6. - if host, port, err := net.SplitHostPort(addr); err == nil { - if port, _ := strconv.Atoi(port); port > 0 { - zone := "" - if i := strings.LastIndex(host, "%"); i >= 0 { - zone = host[i+1:] - host = host[:i] - } - ip := net.ParseIP(host) - if ip != nil { - return &net.TCPAddr{IP: ip, Port: port, Zone: zone}, nil - } - } - } - - // Attempt to resolve IPv4 and v6 concurrently. - addrChan := make(chan *net.TCPAddr, 2) - for _, network := range []string{"udp4", "udp6"} { - network := network - go func() { - // The unfortunate UDP dialing hack allows having a timeout on address resolution. - conn, err := net.DialTimeout(network, addr, 10*time.Second) - if err != nil { - addrChan <- nil - } else { - addrChan <- (*net.TCPAddr)(conn.RemoteAddr().(*net.UDPAddr)) - conn.Close() - } - }() - } - - // Wait for the result of IPv4 and v6 resolution. Use IPv4 if available. - tcpaddr := <-addrChan - if tcpaddr == nil || len(tcpaddr.IP) != 4 { - var timeout <-chan time.Time - if tcpaddr != nil { - // Don't wait too long if an IPv6 address is known. - timeout = time.After(50 * time.Millisecond) - } - select { - case <-timeout: - case tcpaddr2 := <-addrChan: - if tcpaddr == nil || tcpaddr2 != nil { - // It's an IPv4 address or the only known address. Use it. - tcpaddr = tcpaddr2 - } - } - } - - if tcpaddr == nil { - log("SYNC Failed to resolve server address: ", addr) - return nil, errors.New("failed to resolve server address: " + addr) - } - if tcpaddr.String() != addr { - debug("SYNC Address ", addr, " resolved as ", tcpaddr.String()) - } - return tcpaddr, nil -} - -type pendingAdd struct { - server *mongoServer - info *mongoServerInfo -} - -func (cluster *mongoCluster) syncServersIteration(direct bool) { - log("SYNC Starting full topology synchronization...") - - var wg sync.WaitGroup - var m sync.Mutex - notYetAdded := make(map[string]pendingAdd) - addIfFound := make(map[string]bool) - seen := make(map[string]bool) - syncKind := partialSync - - var spawnSync func(addr string, byMaster bool) - spawnSync = func(addr string, byMaster bool) { - wg.Add(1) - go func() { - defer wg.Done() - - tcpaddr, err := resolveAddr(addr) - if err != nil { - log("SYNC Failed to start sync of ", addr, ": ", err.Error()) - return - } - resolvedAddr := tcpaddr.String() - - m.Lock() - if byMaster { - if pending, ok := notYetAdded[resolvedAddr]; ok { - delete(notYetAdded, resolvedAddr) - m.Unlock() - cluster.addServer(pending.server, pending.info, completeSync) - return - } - addIfFound[resolvedAddr] = true - } - if seen[resolvedAddr] { - m.Unlock() - return - } - seen[resolvedAddr] = true - m.Unlock() - - server := cluster.server(addr, tcpaddr) - info, hosts, err := cluster.syncServer(server) - if err != nil { - cluster.removeServer(server) - return - } - - m.Lock() - add := direct || info.Master || addIfFound[resolvedAddr] - if add { - syncKind = completeSync - } else { - notYetAdded[resolvedAddr] = pendingAdd{server, info} - } - m.Unlock() - if add { - cluster.addServer(server, info, completeSync) - } - if !direct { - for _, addr := range hosts { - spawnSync(addr, info.Master) - } - } - }() - } - - knownAddrs := cluster.getKnownAddrs() - for _, addr := range knownAddrs { - spawnSync(addr, false) - } - wg.Wait() - - if syncKind == completeSync { - logf("SYNC Synchronization was complete (got data from primary).") - for _, pending := range notYetAdded { - cluster.removeServer(pending.server) - } - } else { - logf("SYNC Synchronization was partial (cannot talk to primary).") - for _, pending := range notYetAdded { - cluster.addServer(pending.server, pending.info, partialSync) - } - } - - cluster.Lock() - mastersLen := cluster.masters.Len() - logf("SYNC Synchronization completed: %d master(s) and %d slave(s) alive.", mastersLen, cluster.servers.Len()-mastersLen) - - // Update dynamic seeds, but only if we have any good servers. Otherwise, - // leave them alone for better chances of a successful sync in the future. - if syncKind == completeSync { - dynaSeeds := make([]string, cluster.servers.Len()) - for i, server := range cluster.servers.Slice() { - dynaSeeds[i] = server.Addr - } - cluster.dynaSeeds = dynaSeeds - debugf("SYNC New dynamic seeds: %#v\n", dynaSeeds) - } - cluster.Unlock() -} - -// AcquireSocket returns a socket to a server in the cluster. If slaveOk is -// true, it will attempt to return a socket to a slave server. If it is -// false, the socket will necessarily be to a master server. -func (cluster *mongoCluster) AcquireSocket(mode Mode, slaveOk bool, syncTimeout time.Duration, socketTimeout time.Duration, serverTags []bson.D, poolLimit int) (s *mongoSocket, err error) { - var started time.Time - var syncCount uint - warnedLimit := false - for { - cluster.RLock() - for { - mastersLen := cluster.masters.Len() - slavesLen := cluster.servers.Len() - mastersLen - debugf("Cluster has %d known masters and %d known slaves.", mastersLen, slavesLen) - if mastersLen > 0 && !(slaveOk && mode == Secondary) || slavesLen > 0 && slaveOk { - break - } - if mastersLen > 0 && mode == Secondary && cluster.masters.HasMongos() { - break - } - if started.IsZero() { - // Initialize after fast path above. - started = time.Now() - syncCount = cluster.syncCount - } else if syncTimeout != 0 && started.Before(time.Now().Add(-syncTimeout)) || cluster.failFast && cluster.syncCount != syncCount { - cluster.RUnlock() - return nil, errors.New("no reachable servers") - } - log("Waiting for servers to synchronize...") - cluster.syncServers() - - // Remember: this will release and reacquire the lock. - cluster.serverSynced.Wait() - } - - var server *mongoServer - if slaveOk { - server = cluster.servers.BestFit(mode, serverTags) - } else { - server = cluster.masters.BestFit(mode, nil) - } - cluster.RUnlock() - - if server == nil { - // Must have failed the requested tags. Sleep to avoid spinning. - time.Sleep(1e8) - continue - } - - s, abended, err := server.AcquireSocket(poolLimit, socketTimeout) - if err == errPoolLimit { - if !warnedLimit { - warnedLimit = true - log("WARNING: Per-server connection limit reached.") - } - time.Sleep(100 * time.Millisecond) - continue - } - if err != nil { - cluster.removeServer(server) - cluster.syncServers() - continue - } - if abended && !slaveOk { - var result isMasterResult - err := cluster.isMaster(s, &result) - if err != nil || !result.IsMaster { - logf("Cannot confirm server %s as master (%v)", server.Addr, err) - s.Release() - cluster.syncServers() - time.Sleep(100 * time.Millisecond) - continue - } - } - return s, nil - } - panic("unreached") -} - -func (cluster *mongoCluster) CacheIndex(cacheKey string, exists bool) { - cluster.Lock() - if cluster.cachedIndex == nil { - cluster.cachedIndex = make(map[string]bool) - } - if exists { - cluster.cachedIndex[cacheKey] = true - } else { - delete(cluster.cachedIndex, cacheKey) - } - cluster.Unlock() -} - -func (cluster *mongoCluster) HasCachedIndex(cacheKey string) (result bool) { - cluster.RLock() - if cluster.cachedIndex != nil { - result = cluster.cachedIndex[cacheKey] - } - cluster.RUnlock() - return -} - -func (cluster *mongoCluster) ResetIndexCache() { - cluster.Lock() - cluster.cachedIndex = make(map[string]bool) - cluster.Unlock() -} diff --git a/vendor/gopkg.in/mgo.v2/doc.go b/vendor/gopkg.in/mgo.v2/doc.go deleted file mode 100644 index 859fd9b..0000000 --- a/vendor/gopkg.in/mgo.v2/doc.go +++ /dev/null @@ -1,31 +0,0 @@ -// Package mgo offers a rich MongoDB driver for Go. -// -// Details about the mgo project (pronounced as "mango") are found -// in its web page: -// -// http://labix.org/mgo -// -// Usage of the driver revolves around the concept of sessions. To -// get started, obtain a session using the Dial function: -// -// session, err := mgo.Dial(url) -// -// This will establish one or more connections with the cluster of -// servers defined by the url parameter. From then on, the cluster -// may be queried with multiple consistency rules (see SetMode) and -// documents retrieved with statements such as: -// -// c := session.DB(database).C(collection) -// err := c.Find(query).One(&result) -// -// New sessions are typically created by calling session.Copy on the -// initial session obtained at dial time. These new sessions will share -// the same cluster information and connection pool, and may be easily -// handed into other methods and functions for organizing logic. -// Every session created must have its Close method called at the end -// of its life time, so its resources may be put back in the pool or -// collected, depending on the case. -// -// For more details, see the documentation for the types and methods. -// -package mgo diff --git a/vendor/gopkg.in/mgo.v2/gridfs.go b/vendor/gopkg.in/mgo.v2/gridfs.go deleted file mode 100644 index 4214720..0000000 --- a/vendor/gopkg.in/mgo.v2/gridfs.go +++ /dev/null @@ -1,761 +0,0 @@ -// mgo - MongoDB driver for Go -// -// Copyright (c) 2010-2012 - Gustavo Niemeyer -// -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this -// list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR -// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package mgo - -import ( - "crypto/md5" - "encoding/hex" - "errors" - "hash" - "io" - "os" - "sync" - "time" - - "gopkg.in/mgo.v2/bson" -) - -type GridFS struct { - Files *Collection - Chunks *Collection -} - -type gfsFileMode int - -const ( - gfsClosed gfsFileMode = 0 - gfsReading gfsFileMode = 1 - gfsWriting gfsFileMode = 2 -) - -type GridFile struct { - m sync.Mutex - c sync.Cond - gfs *GridFS - mode gfsFileMode - err error - - chunk int - offset int64 - - wpending int - wbuf []byte - wsum hash.Hash - - rbuf []byte - rcache *gfsCachedChunk - - doc gfsFile -} - -type gfsFile struct { - Id interface{} "_id" - ChunkSize int "chunkSize" - UploadDate time.Time "uploadDate" - Length int64 ",minsize" - MD5 string - Filename string ",omitempty" - ContentType string "contentType,omitempty" - Metadata *bson.Raw ",omitempty" -} - -type gfsChunk struct { - Id interface{} "_id" - FilesId interface{} "files_id" - N int - Data []byte -} - -type gfsCachedChunk struct { - wait sync.Mutex - n int - data []byte - err error -} - -func newGridFS(db *Database, prefix string) *GridFS { - return &GridFS{db.C(prefix + ".files"), db.C(prefix + ".chunks")} -} - -func (gfs *GridFS) newFile() *GridFile { - file := &GridFile{gfs: gfs} - file.c.L = &file.m - //runtime.SetFinalizer(file, finalizeFile) - return file -} - -func finalizeFile(file *GridFile) { - file.Close() -} - -// Create creates a new file with the provided name in the GridFS. If the file -// name already exists, a new version will be inserted with an up-to-date -// uploadDate that will cause it to be atomically visible to the Open and -// OpenId methods. If the file name is not important, an empty name may be -// provided and the file Id used instead. -// -// It's important to Close files whether they are being written to -// or read from, and to check the err result to ensure the operation -// completed successfully. -// -// A simple example inserting a new file: -// -// func check(err error) { -// if err != nil { -// panic(err.String()) -// } -// } -// file, err := db.GridFS("fs").Create("myfile.txt") -// check(err) -// n, err := file.Write([]byte("Hello world!")) -// check(err) -// err = file.Close() -// check(err) -// fmt.Printf("%d bytes written\n", n) -// -// The io.Writer interface is implemented by *GridFile and may be used to -// help on the file creation. For example: -// -// file, err := db.GridFS("fs").Create("myfile.txt") -// check(err) -// messages, err := os.Open("/var/log/messages") -// check(err) -// defer messages.Close() -// err = io.Copy(file, messages) -// check(err) -// err = file.Close() -// check(err) -// -func (gfs *GridFS) Create(name string) (file *GridFile, err error) { - file = gfs.newFile() - file.mode = gfsWriting - file.wsum = md5.New() - file.doc = gfsFile{Id: bson.NewObjectId(), ChunkSize: 255 * 1024, Filename: name} - return -} - -// OpenId returns the file with the provided id, for reading. -// If the file isn't found, err will be set to mgo.ErrNotFound. -// -// It's important to Close files whether they are being written to -// or read from, and to check the err result to ensure the operation -// completed successfully. -// -// The following example will print the first 8192 bytes from the file: -// -// func check(err error) { -// if err != nil { -// panic(err.String()) -// } -// } -// file, err := db.GridFS("fs").OpenId(objid) -// check(err) -// b := make([]byte, 8192) -// n, err := file.Read(b) -// check(err) -// fmt.Println(string(b)) -// check(err) -// err = file.Close() -// check(err) -// fmt.Printf("%d bytes read\n", n) -// -// The io.Reader interface is implemented by *GridFile and may be used to -// deal with it. As an example, the following snippet will dump the whole -// file into the standard output: -// -// file, err := db.GridFS("fs").OpenId(objid) -// check(err) -// err = io.Copy(os.Stdout, file) -// check(err) -// err = file.Close() -// check(err) -// -func (gfs *GridFS) OpenId(id interface{}) (file *GridFile, err error) { - var doc gfsFile - err = gfs.Files.Find(bson.M{"_id": id}).One(&doc) - if err != nil { - return - } - file = gfs.newFile() - file.mode = gfsReading - file.doc = doc - return -} - -// Open returns the most recently uploaded file with the provided -// name, for reading. If the file isn't found, err will be set -// to mgo.ErrNotFound. -// -// It's important to Close files whether they are being written to -// or read from, and to check the err result to ensure the operation -// completed successfully. -// -// The following example will print the first 8192 bytes from the file: -// -// file, err := db.GridFS("fs").Open("myfile.txt") -// check(err) -// b := make([]byte, 8192) -// n, err := file.Read(b) -// check(err) -// fmt.Println(string(b)) -// check(err) -// err = file.Close() -// check(err) -// fmt.Printf("%d bytes read\n", n) -// -// The io.Reader interface is implemented by *GridFile and may be used to -// deal with it. As an example, the following snippet will dump the whole -// file into the standard output: -// -// file, err := db.GridFS("fs").Open("myfile.txt") -// check(err) -// err = io.Copy(os.Stdout, file) -// check(err) -// err = file.Close() -// check(err) -// -func (gfs *GridFS) Open(name string) (file *GridFile, err error) { - var doc gfsFile - err = gfs.Files.Find(bson.M{"filename": name}).Sort("-uploadDate").One(&doc) - if err != nil { - return - } - file = gfs.newFile() - file.mode = gfsReading - file.doc = doc - return -} - -// OpenNext opens the next file from iter for reading, sets *file to it, -// and returns true on the success case. If no more documents are available -// on iter or an error occurred, *file is set to nil and the result is false. -// Errors will be available via iter.Err(). -// -// The iter parameter must be an iterator on the GridFS files collection. -// Using the GridFS.Find method is an easy way to obtain such an iterator, -// but any iterator on the collection will work. -// -// If the provided *file is non-nil, OpenNext will close it before attempting -// to iterate to the next element. This means that in a loop one only -// has to worry about closing files when breaking out of the loop early -// (break, return, or panic). -// -// For example: -// -// gfs := db.GridFS("fs") -// query := gfs.Find(nil).Sort("filename") -// iter := query.Iter() -// var f *mgo.GridFile -// for gfs.OpenNext(iter, &f) { -// fmt.Printf("Filename: %s\n", f.Name()) -// } -// if iter.Close() != nil { -// panic(iter.Close()) -// } -// -func (gfs *GridFS) OpenNext(iter *Iter, file **GridFile) bool { - if *file != nil { - // Ignoring the error here shouldn't be a big deal - // as we're reading the file and the loop iteration - // for this file is finished. - _ = (*file).Close() - } - var doc gfsFile - if !iter.Next(&doc) { - *file = nil - return false - } - f := gfs.newFile() - f.mode = gfsReading - f.doc = doc - *file = f - return true -} - -// Find runs query on GridFS's files collection and returns -// the resulting Query. -// -// This logic: -// -// gfs := db.GridFS("fs") -// iter := gfs.Find(nil).Iter() -// -// Is equivalent to: -// -// files := db.C("fs" + ".files") -// iter := files.Find(nil).Iter() -// -func (gfs *GridFS) Find(query interface{}) *Query { - return gfs.Files.Find(query) -} - -// RemoveId deletes the file with the provided id from the GridFS. -func (gfs *GridFS) RemoveId(id interface{}) error { - err := gfs.Files.Remove(bson.M{"_id": id}) - if err != nil { - return err - } - _, err = gfs.Chunks.RemoveAll(bson.D{{"files_id", id}}) - return err -} - -type gfsDocId struct { - Id interface{} "_id" -} - -// Remove deletes all files with the provided name from the GridFS. -func (gfs *GridFS) Remove(name string) (err error) { - iter := gfs.Files.Find(bson.M{"filename": name}).Select(bson.M{"_id": 1}).Iter() - var doc gfsDocId - for iter.Next(&doc) { - if e := gfs.RemoveId(doc.Id); e != nil { - err = e - } - } - if err == nil { - err = iter.Close() - } - return err -} - -func (file *GridFile) assertMode(mode gfsFileMode) { - switch file.mode { - case mode: - return - case gfsWriting: - panic("GridFile is open for writing") - case gfsReading: - panic("GridFile is open for reading") - case gfsClosed: - panic("GridFile is closed") - default: - panic("internal error: missing GridFile mode") - } -} - -// SetChunkSize sets size of saved chunks. Once the file is written to, it -// will be split in blocks of that size and each block saved into an -// independent chunk document. The default chunk size is 255kb. -// -// It is a runtime error to call this function once the file has started -// being written to. -func (file *GridFile) SetChunkSize(bytes int) { - file.assertMode(gfsWriting) - debugf("GridFile %p: setting chunk size to %d", file, bytes) - file.m.Lock() - file.doc.ChunkSize = bytes - file.m.Unlock() -} - -// Id returns the current file Id. -func (file *GridFile) Id() interface{} { - return file.doc.Id -} - -// SetId changes the current file Id. -// -// It is a runtime error to call this function once the file has started -// being written to, or when the file is not open for writing. -func (file *GridFile) SetId(id interface{}) { - file.assertMode(gfsWriting) - file.m.Lock() - file.doc.Id = id - file.m.Unlock() -} - -// Name returns the optional file name. An empty string will be returned -// in case it is unset. -func (file *GridFile) Name() string { - return file.doc.Filename -} - -// SetName changes the optional file name. An empty string may be used to -// unset it. -// -// It is a runtime error to call this function when the file is not open -// for writing. -func (file *GridFile) SetName(name string) { - file.assertMode(gfsWriting) - file.m.Lock() - file.doc.Filename = name - file.m.Unlock() -} - -// ContentType returns the optional file content type. An empty string will be -// returned in case it is unset. -func (file *GridFile) ContentType() string { - return file.doc.ContentType -} - -// ContentType changes the optional file content type. An empty string may be -// used to unset it. -// -// It is a runtime error to call this function when the file is not open -// for writing. -func (file *GridFile) SetContentType(ctype string) { - file.assertMode(gfsWriting) - file.m.Lock() - file.doc.ContentType = ctype - file.m.Unlock() -} - -// GetMeta unmarshals the optional "metadata" field associated with the -// file into the result parameter. The meaning of keys under that field -// is user-defined. For example: -// -// result := struct{ INode int }{} -// err = file.GetMeta(&result) -// if err != nil { -// panic(err.String()) -// } -// fmt.Printf("inode: %d\n", result.INode) -// -func (file *GridFile) GetMeta(result interface{}) (err error) { - file.m.Lock() - if file.doc.Metadata != nil { - err = bson.Unmarshal(file.doc.Metadata.Data, result) - } - file.m.Unlock() - return -} - -// SetMeta changes the optional "metadata" field associated with the -// file. The meaning of keys under that field is user-defined. -// For example: -// -// file.SetMeta(bson.M{"inode": inode}) -// -// It is a runtime error to call this function when the file is not open -// for writing. -func (file *GridFile) SetMeta(metadata interface{}) { - file.assertMode(gfsWriting) - data, err := bson.Marshal(metadata) - file.m.Lock() - if err != nil && file.err == nil { - file.err = err - } else { - file.doc.Metadata = &bson.Raw{Data: data} - } - file.m.Unlock() -} - -// Size returns the file size in bytes. -func (file *GridFile) Size() (bytes int64) { - file.m.Lock() - bytes = file.doc.Length - file.m.Unlock() - return -} - -// MD5 returns the file MD5 as a hex-encoded string. -func (file *GridFile) MD5() (md5 string) { - return file.doc.MD5 -} - -// UploadDate returns the file upload time. -func (file *GridFile) UploadDate() time.Time { - return file.doc.UploadDate -} - -// SetUploadDate changes the file upload time. -// -// It is a runtime error to call this function when the file is not open -// for writing. -func (file *GridFile) SetUploadDate(t time.Time) { - file.assertMode(gfsWriting) - file.m.Lock() - file.doc.UploadDate = t - file.m.Unlock() -} - -// Close flushes any pending changes in case the file is being written -// to, waits for any background operations to finish, and closes the file. -// -// It's important to Close files whether they are being written to -// or read from, and to check the err result to ensure the operation -// completed successfully. -func (file *GridFile) Close() (err error) { - file.m.Lock() - defer file.m.Unlock() - if file.mode == gfsWriting { - if len(file.wbuf) > 0 && file.err == nil { - file.insertChunk(file.wbuf) - file.wbuf = file.wbuf[0:0] - } - file.completeWrite() - } else if file.mode == gfsReading && file.rcache != nil { - file.rcache.wait.Lock() - file.rcache = nil - } - file.mode = gfsClosed - debugf("GridFile %p: closed", file) - return file.err -} - -func (file *GridFile) completeWrite() { - for file.wpending > 0 { - debugf("GridFile %p: waiting for %d pending chunks to complete file write", file, file.wpending) - file.c.Wait() - } - if file.err == nil { - hexsum := hex.EncodeToString(file.wsum.Sum(nil)) - if file.doc.UploadDate.IsZero() { - file.doc.UploadDate = bson.Now() - } - file.doc.MD5 = hexsum - file.err = file.gfs.Files.Insert(file.doc) - } - if file.err != nil { - file.gfs.Chunks.RemoveAll(bson.D{{"files_id", file.doc.Id}}) - } - if file.err == nil { - index := Index{ - Key: []string{"files_id", "n"}, - Unique: true, - } - file.err = file.gfs.Chunks.EnsureIndex(index) - } -} - -// Abort cancels an in-progress write, preventing the file from being -// automically created and ensuring previously written chunks are -// removed when the file is closed. -// -// It is a runtime error to call Abort when the file was not opened -// for writing. -func (file *GridFile) Abort() { - if file.mode != gfsWriting { - panic("file.Abort must be called on file opened for writing") - } - file.err = errors.New("write aborted") -} - -// Write writes the provided data to the file and returns the -// number of bytes written and an error in case something -// wrong happened. -// -// The file will internally cache the data so that all but the last -// chunk sent to the database have the size defined by SetChunkSize. -// This also means that errors may be deferred until a future call -// to Write or Close. -// -// The parameters and behavior of this function turn the file -// into an io.Writer. -func (file *GridFile) Write(data []byte) (n int, err error) { - file.assertMode(gfsWriting) - file.m.Lock() - debugf("GridFile %p: writing %d bytes", file, len(data)) - defer file.m.Unlock() - - if file.err != nil { - return 0, file.err - } - - n = len(data) - file.doc.Length += int64(n) - chunkSize := file.doc.ChunkSize - - if len(file.wbuf)+len(data) < chunkSize { - file.wbuf = append(file.wbuf, data...) - return - } - - // First, flush file.wbuf complementing with data. - if len(file.wbuf) > 0 { - missing := chunkSize - len(file.wbuf) - if missing > len(data) { - missing = len(data) - } - file.wbuf = append(file.wbuf, data[:missing]...) - data = data[missing:] - file.insertChunk(file.wbuf) - file.wbuf = file.wbuf[0:0] - } - - // Then, flush all chunks from data without copying. - for len(data) > chunkSize { - size := chunkSize - if size > len(data) { - size = len(data) - } - file.insertChunk(data[:size]) - data = data[size:] - } - - // And append the rest for a future call. - file.wbuf = append(file.wbuf, data...) - - return n, file.err -} - -func (file *GridFile) insertChunk(data []byte) { - n := file.chunk - file.chunk++ - debugf("GridFile %p: adding to checksum: %q", file, string(data)) - file.wsum.Write(data) - - for file.doc.ChunkSize*file.wpending >= 1024*1024 { - // Hold on.. we got a MB pending. - file.c.Wait() - if file.err != nil { - return - } - } - - file.wpending++ - - debugf("GridFile %p: inserting chunk %d with %d bytes", file, n, len(data)) - - // We may not own the memory of data, so rather than - // simply copying it, we'll marshal the document ahead of time. - data, err := bson.Marshal(gfsChunk{bson.NewObjectId(), file.doc.Id, n, data}) - if err != nil { - file.err = err - return - } - - go func() { - err := file.gfs.Chunks.Insert(bson.Raw{Data: data}) - file.m.Lock() - file.wpending-- - if err != nil && file.err == nil { - file.err = err - } - file.c.Broadcast() - file.m.Unlock() - }() -} - -// Seek sets the offset for the next Read or Write on file to -// offset, interpreted according to whence: 0 means relative to -// the origin of the file, 1 means relative to the current offset, -// and 2 means relative to the end. It returns the new offset and -// an error, if any. -func (file *GridFile) Seek(offset int64, whence int) (pos int64, err error) { - file.m.Lock() - debugf("GridFile %p: seeking for %s (whence=%d)", file, offset, whence) - defer file.m.Unlock() - switch whence { - case os.SEEK_SET: - case os.SEEK_CUR: - offset += file.offset - case os.SEEK_END: - offset += file.doc.Length - default: - panic("unsupported whence value") - } - if offset > file.doc.Length { - return file.offset, errors.New("seek past end of file") - } - if offset == file.doc.Length { - // If we're seeking to the end of the file, - // no need to read anything. This enables - // a client to find the size of the file using only the - // io.ReadSeeker interface with low overhead. - file.offset = offset - return file.offset, nil - } - chunk := int(offset / int64(file.doc.ChunkSize)) - if chunk+1 == file.chunk && offset >= file.offset { - file.rbuf = file.rbuf[int(offset-file.offset):] - file.offset = offset - return file.offset, nil - } - file.offset = offset - file.chunk = chunk - file.rbuf = nil - file.rbuf, err = file.getChunk() - if err == nil { - file.rbuf = file.rbuf[int(file.offset-int64(chunk)*int64(file.doc.ChunkSize)):] - } - return file.offset, err -} - -// Read reads into b the next available data from the file and -// returns the number of bytes written and an error in case -// something wrong happened. At the end of the file, n will -// be zero and err will be set to io.EOF. -// -// The parameters and behavior of this function turn the file -// into an io.Reader. -func (file *GridFile) Read(b []byte) (n int, err error) { - file.assertMode(gfsReading) - file.m.Lock() - debugf("GridFile %p: reading at offset %d into buffer of length %d", file, file.offset, len(b)) - defer file.m.Unlock() - if file.offset == file.doc.Length { - return 0, io.EOF - } - for err == nil { - i := copy(b, file.rbuf) - n += i - file.offset += int64(i) - file.rbuf = file.rbuf[i:] - if i == len(b) || file.offset == file.doc.Length { - break - } - b = b[i:] - file.rbuf, err = file.getChunk() - } - return n, err -} - -func (file *GridFile) getChunk() (data []byte, err error) { - cache := file.rcache - file.rcache = nil - if cache != nil && cache.n == file.chunk { - debugf("GridFile %p: Getting chunk %d from cache", file, file.chunk) - cache.wait.Lock() - data, err = cache.data, cache.err - } else { - debugf("GridFile %p: Fetching chunk %d", file, file.chunk) - var doc gfsChunk - err = file.gfs.Chunks.Find(bson.D{{"files_id", file.doc.Id}, {"n", file.chunk}}).One(&doc) - data = doc.Data - } - file.chunk++ - if int64(file.chunk)*int64(file.doc.ChunkSize) < file.doc.Length { - // Read the next one in background. - cache = &gfsCachedChunk{n: file.chunk} - cache.wait.Lock() - debugf("GridFile %p: Scheduling chunk %d for background caching", file, file.chunk) - // Clone the session to avoid having it closed in between. - chunks := file.gfs.Chunks - session := chunks.Database.Session.Clone() - go func(id interface{}, n int) { - defer session.Close() - chunks = chunks.With(session) - var doc gfsChunk - cache.err = chunks.Find(bson.D{{"files_id", id}, {"n", n}}).One(&doc) - cache.data = doc.Data - cache.wait.Unlock() - }(file.doc.Id, file.chunk) - file.rcache = cache - } - debugf("Returning err: %#v", err) - return -} diff --git a/vendor/gopkg.in/mgo.v2/internal/json/LICENSE b/vendor/gopkg.in/mgo.v2/internal/json/LICENSE deleted file mode 100644 index 7448756..0000000 --- a/vendor/gopkg.in/mgo.v2/internal/json/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -Copyright (c) 2012 The Go Authors. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of Google Inc. nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/gopkg.in/mgo.v2/internal/json/decode.go b/vendor/gopkg.in/mgo.v2/internal/json/decode.go deleted file mode 100644 index ce7c7d2..0000000 --- a/vendor/gopkg.in/mgo.v2/internal/json/decode.go +++ /dev/null @@ -1,1685 +0,0 @@ -// Copyright 2010 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. - -// Represents JSON data structure using native Go types: booleans, floats, -// strings, arrays, and maps. - -package json - -import ( - "bytes" - "encoding" - "encoding/base64" - "errors" - "fmt" - "reflect" - "runtime" - "strconv" - "unicode" - "unicode/utf16" - "unicode/utf8" -) - -// Unmarshal parses the JSON-encoded data and stores the result -// in the value pointed to by v. -// -// Unmarshal uses the inverse of the encodings that -// Marshal uses, allocating maps, slices, and pointers as necessary, -// with the following additional rules: -// -// To unmarshal JSON into a pointer, Unmarshal first handles the case of -// the JSON being the JSON literal null. In that case, Unmarshal sets -// the pointer to nil. Otherwise, Unmarshal unmarshals the JSON into -// the value pointed at by the pointer. If the pointer is nil, Unmarshal -// allocates a new value for it to point to. -// -// To unmarshal JSON into a struct, Unmarshal matches incoming object -// keys to the keys used by Marshal (either the struct field name or its tag), -// preferring an exact match but also accepting a case-insensitive match. -// Unmarshal will only set exported fields of the struct. -// -// To unmarshal JSON into an interface value, -// Unmarshal stores one of these in the interface value: -// -// bool, for JSON booleans -// float64, for JSON numbers -// string, for JSON strings -// []interface{}, for JSON arrays -// map[string]interface{}, for JSON objects -// nil for JSON null -// -// To unmarshal a JSON array into a slice, Unmarshal resets the slice length -// to zero and then appends each element to the slice. -// As a special case, to unmarshal an empty JSON array into a slice, -// Unmarshal replaces the slice with a new empty slice. -// -// To unmarshal a JSON array into a Go array, Unmarshal decodes -// JSON array elements into corresponding Go array elements. -// If the Go array is smaller than the JSON array, -// the additional JSON array elements are discarded. -// If the JSON array is smaller than the Go array, -// the additional Go array elements are set to zero values. -// -// To unmarshal a JSON object into a map, Unmarshal first establishes a map to -// use, If the map is nil, Unmarshal allocates a new map. Otherwise Unmarshal -// reuses the existing map, keeping existing entries. Unmarshal then stores key- -// value pairs from the JSON object into the map. The map's key type must -// either be a string or implement encoding.TextUnmarshaler. -// -// If a JSON value is not appropriate for a given target type, -// or if a JSON number overflows the target type, Unmarshal -// skips that field and completes the unmarshaling as best it can. -// If no more serious errors are encountered, Unmarshal returns -// an UnmarshalTypeError describing the earliest such error. -// -// The JSON null value unmarshals into an interface, map, pointer, or slice -// by setting that Go value to nil. Because null is often used in JSON to mean -// ``not present,'' unmarshaling a JSON null into any other Go type has no effect -// on the value and produces no error. -// -// When unmarshaling quoted strings, invalid UTF-8 or -// invalid UTF-16 surrogate pairs are not treated as an error. -// Instead, they are replaced by the Unicode replacement -// character U+FFFD. -// -func Unmarshal(data []byte, v interface{}) error { - // Check for well-formedness. - // Avoids filling out half a data structure - // before discovering a JSON syntax error. - var d decodeState - err := checkValid(data, &d.scan) - if err != nil { - return err - } - - d.init(data) - return d.unmarshal(v) -} - -// Unmarshaler is the interface implemented by types -// that can unmarshal a JSON description of themselves. -// The input can be assumed to be a valid encoding of -// a JSON value. UnmarshalJSON must copy the JSON data -// if it wishes to retain the data after returning. -type Unmarshaler interface { - UnmarshalJSON([]byte) error -} - -// An UnmarshalTypeError describes a JSON value that was -// not appropriate for a value of a specific Go type. -type UnmarshalTypeError struct { - Value string // description of JSON value - "bool", "array", "number -5" - Type reflect.Type // type of Go value it could not be assigned to - Offset int64 // error occurred after reading Offset bytes -} - -func (e *UnmarshalTypeError) Error() string { - return "json: cannot unmarshal " + e.Value + " into Go value of type " + e.Type.String() -} - -// An UnmarshalFieldError describes a JSON object key that -// led to an unexported (and therefore unwritable) struct field. -// (No longer used; kept for compatibility.) -type UnmarshalFieldError struct { - Key string - Type reflect.Type - Field reflect.StructField -} - -func (e *UnmarshalFieldError) Error() string { - return "json: cannot unmarshal object key " + strconv.Quote(e.Key) + " into unexported field " + e.Field.Name + " of type " + e.Type.String() -} - -// An InvalidUnmarshalError describes an invalid argument passed to Unmarshal. -// (The argument to Unmarshal must be a non-nil pointer.) -type InvalidUnmarshalError struct { - Type reflect.Type -} - -func (e *InvalidUnmarshalError) Error() string { - if e.Type == nil { - return "json: Unmarshal(nil)" - } - - if e.Type.Kind() != reflect.Ptr { - return "json: Unmarshal(non-pointer " + e.Type.String() + ")" - } - return "json: Unmarshal(nil " + e.Type.String() + ")" -} - -func (d *decodeState) unmarshal(v interface{}) (err error) { - defer func() { - if r := recover(); r != nil { - if _, ok := r.(runtime.Error); ok { - panic(r) - } - err = r.(error) - } - }() - - rv := reflect.ValueOf(v) - if rv.Kind() != reflect.Ptr || rv.IsNil() { - return &InvalidUnmarshalError{reflect.TypeOf(v)} - } - - d.scan.reset() - // We decode rv not rv.Elem because the Unmarshaler interface - // test must be applied at the top level of the value. - d.value(rv) - return d.savedError -} - -// A Number represents a JSON number literal. -type Number string - -// String returns the literal text of the number. -func (n Number) String() string { return string(n) } - -// Float64 returns the number as a float64. -func (n Number) Float64() (float64, error) { - return strconv.ParseFloat(string(n), 64) -} - -// Int64 returns the number as an int64. -func (n Number) Int64() (int64, error) { - return strconv.ParseInt(string(n), 10, 64) -} - -// isValidNumber reports whether s is a valid JSON number literal. -func isValidNumber(s string) bool { - // This function implements the JSON numbers grammar. - // See https://tools.ietf.org/html/rfc7159#section-6 - // and http://json.org/number.gif - - if s == "" { - return false - } - - // Optional - - if s[0] == '-' { - s = s[1:] - if s == "" { - return false - } - } - - // Digits - switch { - default: - return false - - case s[0] == '0': - s = s[1:] - - case '1' <= s[0] && s[0] <= '9': - s = s[1:] - for len(s) > 0 && '0' <= s[0] && s[0] <= '9' { - s = s[1:] - } - } - - // . followed by 1 or more digits. - if len(s) >= 2 && s[0] == '.' && '0' <= s[1] && s[1] <= '9' { - s = s[2:] - for len(s) > 0 && '0' <= s[0] && s[0] <= '9' { - s = s[1:] - } - } - - // e or E followed by an optional - or + and - // 1 or more digits. - if len(s) >= 2 && (s[0] == 'e' || s[0] == 'E') { - s = s[1:] - if s[0] == '+' || s[0] == '-' { - s = s[1:] - if s == "" { - return false - } - } - for len(s) > 0 && '0' <= s[0] && s[0] <= '9' { - s = s[1:] - } - } - - // Make sure we are at the end. - return s == "" -} - -// decodeState represents the state while decoding a JSON value. -type decodeState struct { - data []byte - off int // read offset in data - scan scanner - nextscan scanner // for calls to nextValue - savedError error - useNumber bool - ext Extension -} - -// errPhase is used for errors that should not happen unless -// there is a bug in the JSON decoder or something is editing -// the data slice while the decoder executes. -var errPhase = errors.New("JSON decoder out of sync - data changing underfoot?") - -func (d *decodeState) init(data []byte) *decodeState { - d.data = data - d.off = 0 - d.savedError = nil - return d -} - -// error aborts the decoding by panicking with err. -func (d *decodeState) error(err error) { - panic(err) -} - -// saveError saves the first err it is called with, -// for reporting at the end of the unmarshal. -func (d *decodeState) saveError(err error) { - if d.savedError == nil { - d.savedError = err - } -} - -// next cuts off and returns the next full JSON value in d.data[d.off:]. -// The next value is known to be an object or array, not a literal. -func (d *decodeState) next() []byte { - c := d.data[d.off] - item, rest, err := nextValue(d.data[d.off:], &d.nextscan) - if err != nil { - d.error(err) - } - d.off = len(d.data) - len(rest) - - // Our scanner has seen the opening brace/bracket - // and thinks we're still in the middle of the object. - // invent a closing brace/bracket to get it out. - if c == '{' { - d.scan.step(&d.scan, '}') - } else if c == '[' { - d.scan.step(&d.scan, ']') - } else { - // Was inside a function name. Get out of it. - d.scan.step(&d.scan, '(') - d.scan.step(&d.scan, ')') - } - - return item -} - -// scanWhile processes bytes in d.data[d.off:] until it -// receives a scan code not equal to op. -// It updates d.off and returns the new scan code. -func (d *decodeState) scanWhile(op int) int { - var newOp int - for { - if d.off >= len(d.data) { - newOp = d.scan.eof() - d.off = len(d.data) + 1 // mark processed EOF with len+1 - } else { - c := d.data[d.off] - d.off++ - newOp = d.scan.step(&d.scan, c) - } - if newOp != op { - break - } - } - return newOp -} - -// value decodes a JSON value from d.data[d.off:] into the value. -// it updates d.off to point past the decoded value. -func (d *decodeState) value(v reflect.Value) { - if !v.IsValid() { - _, rest, err := nextValue(d.data[d.off:], &d.nextscan) - if err != nil { - d.error(err) - } - d.off = len(d.data) - len(rest) - - // d.scan thinks we're still at the beginning of the item. - // Feed in an empty string - the shortest, simplest value - - // so that it knows we got to the end of the value. - if d.scan.redo { - // rewind. - d.scan.redo = false - d.scan.step = stateBeginValue - } - d.scan.step(&d.scan, '"') - d.scan.step(&d.scan, '"') - - n := len(d.scan.parseState) - if n > 0 && d.scan.parseState[n-1] == parseObjectKey { - // d.scan thinks we just read an object key; finish the object - d.scan.step(&d.scan, ':') - d.scan.step(&d.scan, '"') - d.scan.step(&d.scan, '"') - d.scan.step(&d.scan, '}') - } - - return - } - - switch op := d.scanWhile(scanSkipSpace); op { - default: - d.error(errPhase) - - case scanBeginArray: - d.array(v) - - case scanBeginObject: - d.object(v) - - case scanBeginLiteral: - d.literal(v) - - case scanBeginName: - d.name(v) - } -} - -type unquotedValue struct{} - -// valueQuoted is like value but decodes a -// quoted string literal or literal null into an interface value. -// If it finds anything other than a quoted string literal or null, -// valueQuoted returns unquotedValue{}. -func (d *decodeState) valueQuoted() interface{} { - switch op := d.scanWhile(scanSkipSpace); op { - default: - d.error(errPhase) - - case scanBeginArray: - d.array(reflect.Value{}) - - case scanBeginObject: - d.object(reflect.Value{}) - - case scanBeginName: - switch v := d.nameInterface().(type) { - case nil, string: - return v - } - - case scanBeginLiteral: - switch v := d.literalInterface().(type) { - case nil, string: - return v - } - } - return unquotedValue{} -} - -// indirect walks down v allocating pointers as needed, -// until it gets to a non-pointer. -// if it encounters an Unmarshaler, indirect stops and returns that. -// if decodingNull is true, indirect stops at the last pointer so it can be set to nil. -func (d *decodeState) indirect(v reflect.Value, decodingNull bool) (Unmarshaler, encoding.TextUnmarshaler, reflect.Value) { - // If v is a named type and is addressable, - // start with its address, so that if the type has pointer methods, - // we find them. - if v.Kind() != reflect.Ptr && v.Type().Name() != "" && v.CanAddr() { - v = v.Addr() - } - for { - // Load value from interface, but only if the result will be - // usefully addressable. - if v.Kind() == reflect.Interface && !v.IsNil() { - e := v.Elem() - if e.Kind() == reflect.Ptr && !e.IsNil() && (!decodingNull || e.Elem().Kind() == reflect.Ptr) { - v = e - continue - } - } - - if v.Kind() != reflect.Ptr { - break - } - - if v.Elem().Kind() != reflect.Ptr && decodingNull && v.CanSet() { - break - } - if v.IsNil() { - v.Set(reflect.New(v.Type().Elem())) - } - if v.Type().NumMethod() > 0 { - if u, ok := v.Interface().(Unmarshaler); ok { - return u, nil, v - } - if u, ok := v.Interface().(encoding.TextUnmarshaler); ok { - return nil, u, v - } - } - v = v.Elem() - } - return nil, nil, v -} - -// array consumes an array from d.data[d.off-1:], decoding into the value v. -// the first byte of the array ('[') has been read already. -func (d *decodeState) array(v reflect.Value) { - // Check for unmarshaler. - u, ut, pv := d.indirect(v, false) - if u != nil { - d.off-- - err := u.UnmarshalJSON(d.next()) - if err != nil { - d.error(err) - } - return - } - if ut != nil { - d.saveError(&UnmarshalTypeError{"array", v.Type(), int64(d.off)}) - d.off-- - d.next() - return - } - - v = pv - - // Check type of target. - switch v.Kind() { - case reflect.Interface: - if v.NumMethod() == 0 { - // Decoding into nil interface? Switch to non-reflect code. - v.Set(reflect.ValueOf(d.arrayInterface())) - return - } - // Otherwise it's invalid. - fallthrough - default: - d.saveError(&UnmarshalTypeError{"array", v.Type(), int64(d.off)}) - d.off-- - d.next() - return - case reflect.Array: - case reflect.Slice: - break - } - - i := 0 - for { - // Look ahead for ] - can only happen on first iteration. - op := d.scanWhile(scanSkipSpace) - if op == scanEndArray { - break - } - - // Back up so d.value can have the byte we just read. - d.off-- - d.scan.undo(op) - - // Get element of array, growing if necessary. - if v.Kind() == reflect.Slice { - // Grow slice if necessary - if i >= v.Cap() { - newcap := v.Cap() + v.Cap()/2 - if newcap < 4 { - newcap = 4 - } - newv := reflect.MakeSlice(v.Type(), v.Len(), newcap) - reflect.Copy(newv, v) - v.Set(newv) - } - if i >= v.Len() { - v.SetLen(i + 1) - } - } - - if i < v.Len() { - // Decode into element. - d.value(v.Index(i)) - } else { - // Ran out of fixed array: skip. - d.value(reflect.Value{}) - } - i++ - - // Next token must be , or ]. - op = d.scanWhile(scanSkipSpace) - if op == scanEndArray { - break - } - if op != scanArrayValue { - d.error(errPhase) - } - } - - if i < v.Len() { - if v.Kind() == reflect.Array { - // Array. Zero the rest. - z := reflect.Zero(v.Type().Elem()) - for ; i < v.Len(); i++ { - v.Index(i).Set(z) - } - } else { - v.SetLen(i) - } - } - if i == 0 && v.Kind() == reflect.Slice { - v.Set(reflect.MakeSlice(v.Type(), 0, 0)) - } -} - -var nullLiteral = []byte("null") -var textUnmarshalerType = reflect.TypeOf(new(encoding.TextUnmarshaler)).Elem() - -// object consumes an object from d.data[d.off-1:], decoding into the value v. -// the first byte ('{') of the object has been read already. -func (d *decodeState) object(v reflect.Value) { - // Check for unmarshaler. - u, ut, pv := d.indirect(v, false) - if d.storeKeyed(pv) { - return - } - if u != nil { - d.off-- - err := u.UnmarshalJSON(d.next()) - if err != nil { - d.error(err) - } - return - } - if ut != nil { - d.saveError(&UnmarshalTypeError{"object", v.Type(), int64(d.off)}) - d.off-- - d.next() // skip over { } in input - return - } - v = pv - - // Decoding into nil interface? Switch to non-reflect code. - if v.Kind() == reflect.Interface && v.NumMethod() == 0 { - v.Set(reflect.ValueOf(d.objectInterface())) - return - } - - // Check type of target: - // struct or - // map[string]T or map[encoding.TextUnmarshaler]T - switch v.Kind() { - case reflect.Map: - // Map key must either have string kind or be an encoding.TextUnmarshaler. - t := v.Type() - if t.Key().Kind() != reflect.String && - !reflect.PtrTo(t.Key()).Implements(textUnmarshalerType) { - d.saveError(&UnmarshalTypeError{"object", v.Type(), int64(d.off)}) - d.off-- - d.next() // skip over { } in input - return - } - if v.IsNil() { - v.Set(reflect.MakeMap(t)) - } - case reflect.Struct: - - default: - d.saveError(&UnmarshalTypeError{"object", v.Type(), int64(d.off)}) - d.off-- - d.next() // skip over { } in input - return - } - - var mapElem reflect.Value - - empty := true - for { - // Read opening " of string key or closing }. - op := d.scanWhile(scanSkipSpace) - if op == scanEndObject { - if !empty && !d.ext.trailingCommas { - d.syntaxError("beginning of object key string") - } - break - } - empty = false - if op == scanBeginName { - if !d.ext.unquotedKeys { - d.syntaxError("beginning of object key string") - } - } else if op != scanBeginLiteral { - d.error(errPhase) - } - unquotedKey := op == scanBeginName - - // Read key. - start := d.off - 1 - op = d.scanWhile(scanContinue) - item := d.data[start : d.off-1] - var key []byte - if unquotedKey { - key = item - // TODO Fix code below to quote item when necessary. - } else { - var ok bool - key, ok = unquoteBytes(item) - if !ok { - d.error(errPhase) - } - } - - // Figure out field corresponding to key. - var subv reflect.Value - destring := false // whether the value is wrapped in a string to be decoded first - - if v.Kind() == reflect.Map { - elemType := v.Type().Elem() - if !mapElem.IsValid() { - mapElem = reflect.New(elemType).Elem() - } else { - mapElem.Set(reflect.Zero(elemType)) - } - subv = mapElem - } else { - var f *field - fields := cachedTypeFields(v.Type()) - for i := range fields { - ff := &fields[i] - if bytes.Equal(ff.nameBytes, key) { - f = ff - break - } - if f == nil && ff.equalFold(ff.nameBytes, key) { - f = ff - } - } - if f != nil { - subv = v - destring = f.quoted - for _, i := range f.index { - if subv.Kind() == reflect.Ptr { - if subv.IsNil() { - subv.Set(reflect.New(subv.Type().Elem())) - } - subv = subv.Elem() - } - subv = subv.Field(i) - } - } - } - - // Read : before value. - if op == scanSkipSpace { - op = d.scanWhile(scanSkipSpace) - } - if op != scanObjectKey { - d.error(errPhase) - } - - // Read value. - if destring { - switch qv := d.valueQuoted().(type) { - case nil: - d.literalStore(nullLiteral, subv, false) - case string: - d.literalStore([]byte(qv), subv, true) - default: - d.saveError(fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal unquoted value into %v", subv.Type())) - } - } else { - d.value(subv) - } - - // Write value back to map; - // if using struct, subv points into struct already. - if v.Kind() == reflect.Map { - kt := v.Type().Key() - var kv reflect.Value - switch { - case kt.Kind() == reflect.String: - kv = reflect.ValueOf(key).Convert(v.Type().Key()) - case reflect.PtrTo(kt).Implements(textUnmarshalerType): - kv = reflect.New(v.Type().Key()) - d.literalStore(item, kv, true) - kv = kv.Elem() - default: - panic("json: Unexpected key type") // should never occur - } - v.SetMapIndex(kv, subv) - } - - // Next token must be , or }. - op = d.scanWhile(scanSkipSpace) - if op == scanEndObject { - break - } - if op != scanObjectValue { - d.error(errPhase) - } - } -} - -// isNull returns whether there's a null literal at the provided offset. -func (d *decodeState) isNull(off int) bool { - if off+4 >= len(d.data) || d.data[off] != 'n' || d.data[off+1] != 'u' || d.data[off+2] != 'l' || d.data[off+3] != 'l' { - return false - } - d.nextscan.reset() - for i, c := range d.data[off:] { - if i > 4 { - return false - } - switch d.nextscan.step(&d.nextscan, c) { - case scanContinue, scanBeginName: - continue - } - break - } - return true -} - -// name consumes a const or function from d.data[d.off-1:], decoding into the value v. -// the first byte of the function name has been read already. -func (d *decodeState) name(v reflect.Value) { - if d.isNull(d.off-1) { - d.literal(v) - return - } - - // Check for unmarshaler. - u, ut, pv := d.indirect(v, false) - if d.storeKeyed(pv) { - return - } - if u != nil { - d.off-- - err := u.UnmarshalJSON(d.next()) - if err != nil { - d.error(err) - } - return - } - if ut != nil { - d.saveError(&UnmarshalTypeError{"object", v.Type(), int64(d.off)}) - d.off-- - d.next() // skip over function in input - return - } - v = pv - - // Decoding into nil interface? Switch to non-reflect code. - if v.Kind() == reflect.Interface && v.NumMethod() == 0 { - out := d.nameInterface() - if out == nil { - v.Set(reflect.Zero(v.Type())) - } else { - v.Set(reflect.ValueOf(out)) - } - return - } - - nameStart := d.off - 1 - - op := d.scanWhile(scanContinue) - - name := d.data[nameStart : d.off-1] - if op != scanParam { - // Back up so the byte just read is consumed next. - d.off-- - d.scan.undo(op) - if l, ok := d.convertLiteral(name); ok { - d.storeValue(v, l) - return - } - d.error(&SyntaxError{fmt.Sprintf("json: unknown constant %q", name), int64(d.off)}) - } - - funcName := string(name) - funcData := d.ext.funcs[funcName] - if funcData.key == "" { - d.error(fmt.Errorf("json: unknown function %q", funcName)) - } - - // Check type of target: - // struct or - // map[string]T or map[encoding.TextUnmarshaler]T - switch v.Kind() { - case reflect.Map: - // Map key must either have string kind or be an encoding.TextUnmarshaler. - t := v.Type() - if t.Key().Kind() != reflect.String && - !reflect.PtrTo(t.Key()).Implements(textUnmarshalerType) { - d.saveError(&UnmarshalTypeError{"object", v.Type(), int64(d.off)}) - d.off-- - d.next() // skip over { } in input - return - } - if v.IsNil() { - v.Set(reflect.MakeMap(t)) - } - case reflect.Struct: - - default: - d.saveError(&UnmarshalTypeError{"object", v.Type(), int64(d.off)}) - d.off-- - d.next() // skip over { } in input - return - } - - // TODO Fix case of func field as map. - //topv := v - - // Figure out field corresponding to function. - key := []byte(funcData.key) - if v.Kind() == reflect.Map { - elemType := v.Type().Elem() - v = reflect.New(elemType).Elem() - } else { - var f *field - fields := cachedTypeFields(v.Type()) - for i := range fields { - ff := &fields[i] - if bytes.Equal(ff.nameBytes, key) { - f = ff - break - } - if f == nil && ff.equalFold(ff.nameBytes, key) { - f = ff - } - } - if f != nil { - for _, i := range f.index { - if v.Kind() == reflect.Ptr { - if v.IsNil() { - v.Set(reflect.New(v.Type().Elem())) - } - v = v.Elem() - } - v = v.Field(i) - } - if v.Kind() == reflect.Ptr { - if v.IsNil() { - v.Set(reflect.New(v.Type().Elem())) - } - v = v.Elem() - } - } - } - - // Check for unmarshaler on func field itself. - u, ut, pv = d.indirect(v, false) - if u != nil { - d.off = nameStart - err := u.UnmarshalJSON(d.next()) - if err != nil { - d.error(err) - } - return - } - - var mapElem reflect.Value - - // Parse function arguments. - for i := 0; ; i++ { - // closing ) - can only happen on first iteration. - op := d.scanWhile(scanSkipSpace) - if op == scanEndParams { - break - } - - // Back up so d.value can have the byte we just read. - d.off-- - d.scan.undo(op) - - if i >= len(funcData.args) { - d.error(fmt.Errorf("json: too many arguments for function %s", funcName)) - } - key := []byte(funcData.args[i]) - - // Figure out field corresponding to key. - var subv reflect.Value - destring := false // whether the value is wrapped in a string to be decoded first - - if v.Kind() == reflect.Map { - elemType := v.Type().Elem() - if !mapElem.IsValid() { - mapElem = reflect.New(elemType).Elem() - } else { - mapElem.Set(reflect.Zero(elemType)) - } - subv = mapElem - } else { - var f *field - fields := cachedTypeFields(v.Type()) - for i := range fields { - ff := &fields[i] - if bytes.Equal(ff.nameBytes, key) { - f = ff - break - } - if f == nil && ff.equalFold(ff.nameBytes, key) { - f = ff - } - } - if f != nil { - subv = v - destring = f.quoted - for _, i := range f.index { - if subv.Kind() == reflect.Ptr { - if subv.IsNil() { - subv.Set(reflect.New(subv.Type().Elem())) - } - subv = subv.Elem() - } - subv = subv.Field(i) - } - } - } - - // Read value. - if destring { - switch qv := d.valueQuoted().(type) { - case nil: - d.literalStore(nullLiteral, subv, false) - case string: - d.literalStore([]byte(qv), subv, true) - default: - d.saveError(fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal unquoted value into %v", subv.Type())) - } - } else { - d.value(subv) - } - - // Write value back to map; - // if using struct, subv points into struct already. - if v.Kind() == reflect.Map { - kt := v.Type().Key() - var kv reflect.Value - switch { - case kt.Kind() == reflect.String: - kv = reflect.ValueOf(key).Convert(v.Type().Key()) - case reflect.PtrTo(kt).Implements(textUnmarshalerType): - kv = reflect.New(v.Type().Key()) - d.literalStore(key, kv, true) - kv = kv.Elem() - default: - panic("json: Unexpected key type") // should never occur - } - v.SetMapIndex(kv, subv) - } - - // Next token must be , or ). - op = d.scanWhile(scanSkipSpace) - if op == scanEndParams { - break - } - if op != scanParam { - d.error(errPhase) - } - } -} - -// keyed attempts to decode an object or function using a keyed doc extension, -// and returns the value and true on success, or nil and false otherwise. -func (d *decodeState) keyed() (interface{}, bool) { - if len(d.ext.keyed) == 0 { - return nil, false - } - - unquote := false - - // Look-ahead first key to check for a keyed document extension. - d.nextscan.reset() - var start, end int - for i, c := range d.data[d.off-1:] { - switch op := d.nextscan.step(&d.nextscan, c); op { - case scanSkipSpace, scanContinue, scanBeginObject: - continue - case scanBeginLiteral, scanBeginName: - unquote = op == scanBeginLiteral - start = i - continue - } - end = i - break - } - - name := d.data[d.off-1+start : d.off-1+end] - - var key []byte - var ok bool - if unquote { - key, ok = unquoteBytes(name) - if !ok { - d.error(errPhase) - } - } else { - funcData, ok := d.ext.funcs[string(name)] - if !ok { - return nil, false - } - key = []byte(funcData.key) - } - - decode, ok := d.ext.keyed[string(key)] - if !ok { - return nil, false - } - - d.off-- - out, err := decode(d.next()) - if err != nil { - d.error(err) - } - return out, true -} - -func (d *decodeState) storeKeyed(v reflect.Value) bool { - keyed, ok := d.keyed() - if !ok { - return false - } - d.storeValue(v, keyed) - return true -} - -var ( - trueBytes = []byte("true") - falseBytes = []byte("false") - nullBytes = []byte("null") -) - -func (d *decodeState) storeValue(v reflect.Value, from interface{}) { - switch from { - case nil: - d.literalStore(nullBytes, v, false) - return - case true: - d.literalStore(trueBytes, v, false) - return - case false: - d.literalStore(falseBytes, v, false) - return - } - fromv := reflect.ValueOf(from) - for fromv.Kind() == reflect.Ptr && !fromv.IsNil() { - fromv = fromv.Elem() - } - fromt := fromv.Type() - for v.Kind() == reflect.Ptr && !v.IsNil() { - v = v.Elem() - } - vt := v.Type() - if fromt.AssignableTo(vt) { - v.Set(fromv) - } else if fromt.ConvertibleTo(vt) { - v.Set(fromv.Convert(vt)) - } else { - d.saveError(&UnmarshalTypeError{"object", v.Type(), int64(d.off)}) - } -} - -func (d *decodeState) convertLiteral(name []byte) (interface{}, bool) { - if len(name) == 0 { - return nil, false - } - switch name[0] { - case 't': - if bytes.Equal(name, trueBytes) { - return true, true - } - case 'f': - if bytes.Equal(name, falseBytes) { - return false, true - } - case 'n': - if bytes.Equal(name, nullBytes) { - return nil, true - } - } - if l, ok := d.ext.consts[string(name)]; ok { - return l, true - } - return nil, false -} - -// literal consumes a literal from d.data[d.off-1:], decoding into the value v. -// The first byte of the literal has been read already -// (that's how the caller knows it's a literal). -func (d *decodeState) literal(v reflect.Value) { - // All bytes inside literal return scanContinue op code. - start := d.off - 1 - op := d.scanWhile(scanContinue) - - // Scan read one byte too far; back up. - d.off-- - d.scan.undo(op) - - d.literalStore(d.data[start:d.off], v, false) -} - -// convertNumber converts the number literal s to a float64 or a Number -// depending on the setting of d.useNumber. -func (d *decodeState) convertNumber(s string) (interface{}, error) { - if d.useNumber { - return Number(s), nil - } - f, err := strconv.ParseFloat(s, 64) - if err != nil { - return nil, &UnmarshalTypeError{"number " + s, reflect.TypeOf(0.0), int64(d.off)} - } - return f, nil -} - -var numberType = reflect.TypeOf(Number("")) - -// literalStore decodes a literal stored in item into v. -// -// fromQuoted indicates whether this literal came from unwrapping a -// string from the ",string" struct tag option. this is used only to -// produce more helpful error messages. -func (d *decodeState) literalStore(item []byte, v reflect.Value, fromQuoted bool) { - // Check for unmarshaler. - if len(item) == 0 { - //Empty string given - d.saveError(fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type())) - return - } - wantptr := item[0] == 'n' // null - u, ut, pv := d.indirect(v, wantptr) - if u != nil { - err := u.UnmarshalJSON(item) - if err != nil { - d.error(err) - } - return - } - if ut != nil { - if item[0] != '"' { - if fromQuoted { - d.saveError(fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type())) - } else { - d.saveError(&UnmarshalTypeError{"string", v.Type(), int64(d.off)}) - } - return - } - s, ok := unquoteBytes(item) - if !ok { - if fromQuoted { - d.error(fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type())) - } else { - d.error(errPhase) - } - } - err := ut.UnmarshalText(s) - if err != nil { - d.error(err) - } - return - } - - v = pv - - switch c := item[0]; c { - case 'n': // null - switch v.Kind() { - case reflect.Interface, reflect.Ptr, reflect.Map, reflect.Slice: - v.Set(reflect.Zero(v.Type())) - // otherwise, ignore null for primitives/string - } - case 't', 'f': // true, false - value := c == 't' - switch v.Kind() { - default: - if fromQuoted { - d.saveError(fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type())) - } else { - d.saveError(&UnmarshalTypeError{"bool", v.Type(), int64(d.off)}) - } - case reflect.Bool: - v.SetBool(value) - case reflect.Interface: - if v.NumMethod() == 0 { - v.Set(reflect.ValueOf(value)) - } else { - d.saveError(&UnmarshalTypeError{"bool", v.Type(), int64(d.off)}) - } - } - - case '"': // string - s, ok := unquoteBytes(item) - if !ok { - if fromQuoted { - d.error(fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type())) - } else { - d.error(errPhase) - } - } - switch v.Kind() { - default: - d.saveError(&UnmarshalTypeError{"string", v.Type(), int64(d.off)}) - case reflect.Slice: - if v.Type().Elem().Kind() != reflect.Uint8 { - d.saveError(&UnmarshalTypeError{"string", v.Type(), int64(d.off)}) - break - } - b := make([]byte, base64.StdEncoding.DecodedLen(len(s))) - n, err := base64.StdEncoding.Decode(b, s) - if err != nil { - d.saveError(err) - break - } - v.SetBytes(b[:n]) - case reflect.String: - v.SetString(string(s)) - case reflect.Interface: - if v.NumMethod() == 0 { - v.Set(reflect.ValueOf(string(s))) - } else { - d.saveError(&UnmarshalTypeError{"string", v.Type(), int64(d.off)}) - } - } - - default: // number - if c != '-' && (c < '0' || c > '9') { - if fromQuoted { - d.error(fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type())) - } else { - d.error(errPhase) - } - } - s := string(item) - switch v.Kind() { - default: - if v.Kind() == reflect.String && v.Type() == numberType { - v.SetString(s) - if !isValidNumber(s) { - d.error(fmt.Errorf("json: invalid number literal, trying to unmarshal %q into Number", item)) - } - break - } - if fromQuoted { - d.error(fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type())) - } else { - d.error(&UnmarshalTypeError{"number", v.Type(), int64(d.off)}) - } - case reflect.Interface: - n, err := d.convertNumber(s) - if err != nil { - d.saveError(err) - break - } - if v.NumMethod() != 0 { - d.saveError(&UnmarshalTypeError{"number", v.Type(), int64(d.off)}) - break - } - v.Set(reflect.ValueOf(n)) - - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - n, err := strconv.ParseInt(s, 10, 64) - if err != nil || v.OverflowInt(n) { - d.saveError(&UnmarshalTypeError{"number " + s, v.Type(), int64(d.off)}) - break - } - v.SetInt(n) - - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - n, err := strconv.ParseUint(s, 10, 64) - if err != nil || v.OverflowUint(n) { - d.saveError(&UnmarshalTypeError{"number " + s, v.Type(), int64(d.off)}) - break - } - v.SetUint(n) - - case reflect.Float32, reflect.Float64: - n, err := strconv.ParseFloat(s, v.Type().Bits()) - if err != nil || v.OverflowFloat(n) { - d.saveError(&UnmarshalTypeError{"number " + s, v.Type(), int64(d.off)}) - break - } - v.SetFloat(n) - } - } -} - -// The xxxInterface routines build up a value to be stored -// in an empty interface. They are not strictly necessary, -// but they avoid the weight of reflection in this common case. - -// valueInterface is like value but returns interface{} -func (d *decodeState) valueInterface() interface{} { - switch d.scanWhile(scanSkipSpace) { - default: - d.error(errPhase) - panic("unreachable") - case scanBeginArray: - return d.arrayInterface() - case scanBeginObject: - return d.objectInterface() - case scanBeginLiteral: - return d.literalInterface() - case scanBeginName: - return d.nameInterface() - } -} - -func (d *decodeState) syntaxError(expected string) { - msg := fmt.Sprintf("invalid character '%c' looking for %s", d.data[d.off-1], expected) - d.error(&SyntaxError{msg, int64(d.off)}) -} - -// arrayInterface is like array but returns []interface{}. -func (d *decodeState) arrayInterface() []interface{} { - var v = make([]interface{}, 0) - for { - // Look ahead for ] - can only happen on first iteration. - op := d.scanWhile(scanSkipSpace) - if op == scanEndArray { - if len(v) > 0 && !d.ext.trailingCommas { - d.syntaxError("beginning of value") - } - break - } - - // Back up so d.value can have the byte we just read. - d.off-- - d.scan.undo(op) - - v = append(v, d.valueInterface()) - - // Next token must be , or ]. - op = d.scanWhile(scanSkipSpace) - if op == scanEndArray { - break - } - if op != scanArrayValue { - d.error(errPhase) - } - } - return v -} - -// objectInterface is like object but returns map[string]interface{}. -func (d *decodeState) objectInterface() interface{} { - v, ok := d.keyed() - if ok { - return v - } - - m := make(map[string]interface{}) - for { - // Read opening " of string key or closing }. - op := d.scanWhile(scanSkipSpace) - if op == scanEndObject { - if len(m) > 0 && !d.ext.trailingCommas { - d.syntaxError("beginning of object key string") - } - break - } - if op == scanBeginName { - if !d.ext.unquotedKeys { - d.syntaxError("beginning of object key string") - } - } else if op != scanBeginLiteral { - d.error(errPhase) - } - unquotedKey := op == scanBeginName - - // Read string key. - start := d.off - 1 - op = d.scanWhile(scanContinue) - item := d.data[start : d.off-1] - var key string - if unquotedKey { - key = string(item) - } else { - var ok bool - key, ok = unquote(item) - if !ok { - d.error(errPhase) - } - } - - // Read : before value. - if op == scanSkipSpace { - op = d.scanWhile(scanSkipSpace) - } - if op != scanObjectKey { - d.error(errPhase) - } - - // Read value. - m[key] = d.valueInterface() - - // Next token must be , or }. - op = d.scanWhile(scanSkipSpace) - if op == scanEndObject { - break - } - if op != scanObjectValue { - d.error(errPhase) - } - } - return m -} - -// literalInterface is like literal but returns an interface value. -func (d *decodeState) literalInterface() interface{} { - // All bytes inside literal return scanContinue op code. - start := d.off - 1 - op := d.scanWhile(scanContinue) - - // Scan read one byte too far; back up. - d.off-- - d.scan.undo(op) - item := d.data[start:d.off] - - switch c := item[0]; c { - case 'n': // null - return nil - - case 't', 'f': // true, false - return c == 't' - - case '"': // string - s, ok := unquote(item) - if !ok { - d.error(errPhase) - } - return s - - default: // number - if c != '-' && (c < '0' || c > '9') { - d.error(errPhase) - } - n, err := d.convertNumber(string(item)) - if err != nil { - d.saveError(err) - } - return n - } -} - -// nameInterface is like function but returns map[string]interface{}. -func (d *decodeState) nameInterface() interface{} { - v, ok := d.keyed() - if ok { - return v - } - - nameStart := d.off - 1 - - op := d.scanWhile(scanContinue) - - name := d.data[nameStart : d.off-1] - if op != scanParam { - // Back up so the byte just read is consumed next. - d.off-- - d.scan.undo(op) - if l, ok := d.convertLiteral(name); ok { - return l - } - d.error(&SyntaxError{fmt.Sprintf("json: unknown constant %q", name), int64(d.off)}) - } - - funcName := string(name) - funcData := d.ext.funcs[funcName] - if funcData.key == "" { - d.error(fmt.Errorf("json: unknown function %q", funcName)) - } - - m := make(map[string]interface{}) - for i := 0; ; i++ { - // Look ahead for ) - can only happen on first iteration. - op := d.scanWhile(scanSkipSpace) - if op == scanEndParams { - break - } - - // Back up so d.value can have the byte we just read. - d.off-- - d.scan.undo(op) - - if i >= len(funcData.args) { - d.error(fmt.Errorf("json: too many arguments for function %s", funcName)) - } - m[funcData.args[i]] = d.valueInterface() - - // Next token must be , or ). - op = d.scanWhile(scanSkipSpace) - if op == scanEndParams { - break - } - if op != scanParam { - d.error(errPhase) - } - } - return map[string]interface{}{funcData.key: m} -} - -// getu4 decodes \uXXXX from the beginning of s, returning the hex value, -// or it returns -1. -func getu4(s []byte) rune { - if len(s) < 6 || s[0] != '\\' || s[1] != 'u' { - return -1 - } - r, err := strconv.ParseUint(string(s[2:6]), 16, 64) - if err != nil { - return -1 - } - return rune(r) -} - -// unquote converts a quoted JSON string literal s into an actual string t. -// The rules are different than for Go, so cannot use strconv.Unquote. -func unquote(s []byte) (t string, ok bool) { - s, ok = unquoteBytes(s) - t = string(s) - return -} - -func unquoteBytes(s []byte) (t []byte, ok bool) { - if len(s) < 2 || s[0] != '"' || s[len(s)-1] != '"' { - return - } - s = s[1 : len(s)-1] - - // Check for unusual characters. If there are none, - // then no unquoting is needed, so return a slice of the - // original bytes. - r := 0 - for r < len(s) { - c := s[r] - if c == '\\' || c == '"' || c < ' ' { - break - } - if c < utf8.RuneSelf { - r++ - continue - } - rr, size := utf8.DecodeRune(s[r:]) - if rr == utf8.RuneError && size == 1 { - break - } - r += size - } - if r == len(s) { - return s, true - } - - b := make([]byte, len(s)+2*utf8.UTFMax) - w := copy(b, s[0:r]) - for r < len(s) { - // Out of room? Can only happen if s is full of - // malformed UTF-8 and we're replacing each - // byte with RuneError. - if w >= len(b)-2*utf8.UTFMax { - nb := make([]byte, (len(b)+utf8.UTFMax)*2) - copy(nb, b[0:w]) - b = nb - } - switch c := s[r]; { - case c == '\\': - r++ - if r >= len(s) { - return - } - switch s[r] { - default: - return - case '"', '\\', '/', '\'': - b[w] = s[r] - r++ - w++ - case 'b': - b[w] = '\b' - r++ - w++ - case 'f': - b[w] = '\f' - r++ - w++ - case 'n': - b[w] = '\n' - r++ - w++ - case 'r': - b[w] = '\r' - r++ - w++ - case 't': - b[w] = '\t' - r++ - w++ - case 'u': - r-- - rr := getu4(s[r:]) - if rr < 0 { - return - } - r += 6 - if utf16.IsSurrogate(rr) { - rr1 := getu4(s[r:]) - if dec := utf16.DecodeRune(rr, rr1); dec != unicode.ReplacementChar { - // A valid pair; consume. - r += 6 - w += utf8.EncodeRune(b[w:], dec) - break - } - // Invalid surrogate; fall back to replacement rune. - rr = unicode.ReplacementChar - } - w += utf8.EncodeRune(b[w:], rr) - } - - // Quote, control characters are invalid. - case c == '"', c < ' ': - return - - // ASCII - case c < utf8.RuneSelf: - b[w] = c - r++ - w++ - - // Coerce to well-formed UTF-8. - default: - rr, size := utf8.DecodeRune(s[r:]) - r += size - w += utf8.EncodeRune(b[w:], rr) - } - } - return b[0:w], true -} diff --git a/vendor/gopkg.in/mgo.v2/internal/json/encode.go b/vendor/gopkg.in/mgo.v2/internal/json/encode.go deleted file mode 100644 index 67a0f00..0000000 --- a/vendor/gopkg.in/mgo.v2/internal/json/encode.go +++ /dev/null @@ -1,1256 +0,0 @@ -// Copyright 2010 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 json implements encoding and decoding of JSON as defined in -// RFC 4627. The mapping between JSON and Go values is described -// in the documentation for the Marshal and Unmarshal functions. -// -// See "JSON and Go" for an introduction to this package: -// https://golang.org/doc/articles/json_and_go.html -package json - -import ( - "bytes" - "encoding" - "encoding/base64" - "fmt" - "math" - "reflect" - "runtime" - "sort" - "strconv" - "strings" - "sync" - "unicode" - "unicode/utf8" -) - -// Marshal returns the JSON encoding of v. -// -// Marshal traverses the value v recursively. -// If an encountered value implements the Marshaler interface -// and is not a nil pointer, Marshal calls its MarshalJSON method -// to produce JSON. If no MarshalJSON method is present but the -// value implements encoding.TextMarshaler instead, Marshal calls -// its MarshalText method. -// The nil pointer exception is not strictly necessary -// but mimics a similar, necessary exception in the behavior of -// UnmarshalJSON. -// -// Otherwise, Marshal uses the following type-dependent default encodings: -// -// Boolean values encode as JSON booleans. -// -// Floating point, integer, and Number values encode as JSON numbers. -// -// String values encode as JSON strings coerced to valid UTF-8, -// replacing invalid bytes with the Unicode replacement rune. -// The angle brackets "<" and ">" are escaped to "\u003c" and "\u003e" -// to keep some browsers from misinterpreting JSON output as HTML. -// Ampersand "&" is also escaped to "\u0026" for the same reason. -// This escaping can be disabled using an Encoder with DisableHTMLEscaping. -// -// Array and slice values encode as JSON arrays, except that -// []byte encodes as a base64-encoded string, and a nil slice -// encodes as the null JSON value. -// -// Struct values encode as JSON objects. Each exported struct field -// becomes a member of the object unless -// - the field's tag is "-", or -// - the field is empty and its tag specifies the "omitempty" option. -// The empty values are false, 0, any -// nil pointer or interface value, and any array, slice, map, or string of -// length zero. The object's default key string is the struct field name -// but can be specified in the struct field's tag value. The "json" key in -// the struct field's tag value is the key name, followed by an optional comma -// and options. Examples: -// -// // Field is ignored by this package. -// Field int `json:"-"` -// -// // Field appears in JSON as key "myName". -// Field int `json:"myName"` -// -// // Field appears in JSON as key "myName" and -// // the field is omitted from the object if its value is empty, -// // as defined above. -// Field int `json:"myName,omitempty"` -// -// // Field appears in JSON as key "Field" (the default), but -// // the field is skipped if empty. -// // Note the leading comma. -// Field int `json:",omitempty"` -// -// The "string" option signals that a field is stored as JSON inside a -// JSON-encoded string. It applies only to fields of string, floating point, -// integer, or boolean types. This extra level of encoding is sometimes used -// when communicating with JavaScript programs: -// -// Int64String int64 `json:",string"` -// -// The key name will be used if it's a non-empty string consisting of -// only Unicode letters, digits, dollar signs, percent signs, hyphens, -// underscores and slashes. -// -// Anonymous struct fields are usually marshaled as if their inner exported fields -// were fields in the outer struct, subject to the usual Go visibility rules amended -// as described in the next paragraph. -// An anonymous struct field with a name given in its JSON tag is treated as -// having that name, rather than being anonymous. -// An anonymous struct field of interface type is treated the same as having -// that type as its name, rather than being anonymous. -// -// The Go visibility rules for struct fields are amended for JSON when -// deciding which field to marshal or unmarshal. If there are -// multiple fields at the same level, and that level is the least -// nested (and would therefore be the nesting level selected by the -// usual Go rules), the following extra rules apply: -// -// 1) Of those fields, if any are JSON-tagged, only tagged fields are considered, -// even if there are multiple untagged fields that would otherwise conflict. -// 2) If there is exactly one field (tagged or not according to the first rule), that is selected. -// 3) Otherwise there are multiple fields, and all are ignored; no error occurs. -// -// Handling of anonymous struct fields is new in Go 1.1. -// Prior to Go 1.1, anonymous struct fields were ignored. To force ignoring of -// an anonymous struct field in both current and earlier versions, give the field -// a JSON tag of "-". -// -// Map values encode as JSON objects. The map's key type must either be a string -// or implement encoding.TextMarshaler. The map keys are used as JSON object -// keys, subject to the UTF-8 coercion described for string values above. -// -// Pointer values encode as the value pointed to. -// A nil pointer encodes as the null JSON value. -// -// Interface values encode as the value contained in the interface. -// A nil interface value encodes as the null JSON value. -// -// Channel, complex, and function values cannot be encoded in JSON. -// Attempting to encode such a value causes Marshal to return -// an UnsupportedTypeError. -// -// JSON cannot represent cyclic data structures and Marshal does not -// handle them. Passing cyclic structures to Marshal will result in -// an infinite recursion. -// -func Marshal(v interface{}) ([]byte, error) { - e := &encodeState{} - err := e.marshal(v, encOpts{escapeHTML: true}) - if err != nil { - return nil, err - } - return e.Bytes(), nil -} - -// MarshalIndent is like Marshal but applies Indent to format the output. -func MarshalIndent(v interface{}, prefix, indent string) ([]byte, error) { - b, err := Marshal(v) - if err != nil { - return nil, err - } - var buf bytes.Buffer - err = Indent(&buf, b, prefix, indent) - if err != nil { - return nil, err - } - return buf.Bytes(), nil -} - -// HTMLEscape appends to dst the JSON-encoded src with <, >, &, U+2028 and U+2029 -// characters inside string literals changed to \u003c, \u003e, \u0026, \u2028, \u2029 -// so that the JSON will be safe to embed inside HTML